Table of contents

In Unity, objects move because of scripts: C# files that you attach to an object. After you press Play, Unity keeps running the code in the script, and the object moves accordingly. When you write your first script in Unity 7, there is one thing to know up front. If you press Stop and then Play again, any number a script keeps in a static field does not reset, so the second Play continues from the value of the first. This article walks you through writing a script that spins a cube and making those numbers start from scratch on every Play.
The article uses a project created from the Universal 3D template. If you don’t have a project yet, follow Claude & Unity project creation to create one. I tested on Windows 11 with Unity 7000.0.0a23 (Alpha). The interface and default values may still change before the release version.
Create your first script
Once the project is open, create a script that spins a cube:
- In the Project window at the bottom of the Editor, right-click the Assets folder.
- Select Create > Scripting > MonoBehaviour Script. The first level of the Create menu has the same item, and both create exactly the same file.
- Name the file
Spinnerand press Enter. When a script icon named Spinner appears in Assets, the script has been created.

The Spinner.cs that Unity generates already contains empty Start and Update methods, the same as in the official guide to creating scripts.
Double-click Spinner.cs and Unity opens it in your code editor. If you don’t have one yet, you can add the Visual Studio module in Unity Hub, or set up VS Code by following Set up Unity with VS Code or Cursor. Once the file is open, replace its whole content with the following code, which spins the cube 90 degrees per second:
1using UnityEngine;
2
3public class Spinner : MonoBehaviour
4{
5 [SerializeField] float degreesPerSecond = 90f;
6
7 void Update()
8 {
9 transform.Rotate(0f, degreesPerSecond * Time.deltaTime, 0f);
10 }
11}
Update runs once every time the screen refreshes, and transform.Rotate turns the object a small step around the vertical axis. Multiplying by Time.deltaTime keeps the rotation speed per second constant, whether the computer is fast or slow. [SerializeField] makes the speed show up in the Inspector window, so you can change it without editing the code.
After you save the file, attach the script to a cube:
-
Go back to Unity. A spinning icon and a “Compiling Scripts” progress bar appear at the bottom right. When they disappear and the icon turns back into a circle with a check mark, Unity has finished compiling the script.

-
In the Hierarchy window on the left, click “+” at the top left and select 3D Object > Cube to create a cube. The Hierarchy lists every object in the scene.

-
Drag
Spinnerfrom the Project window onto the Cube in the Hierarchy. When you select the Cube and the Inspector on the right shows a Spinner component, the script is attached. -
Click the Play button at the top of the screen. When the cube starts spinning, the script is running.
-
Click Play again to stop.
Once the script is attached, the Cube’s Inspector has a new Spinner component. “Degrees Per Second” is the degreesPerSecond field from the code, and its default is 90:

After you press Play, the cube in the Game window keeps turning around the vertical axis:

Reset static values on every Play
Games often use a number to track a score or a death count. If you put static in front of a field, the value belongs to the class itself instead of one object, and every object with that script shares it. To shorten the wait when you press Play, new Unity 7 projects do not reload scripts when you enter Play Mode, so a static field keeps the value from the previous Play.
To check how your project is set up, open Edit > Project Settings, select Editor on the left, and scroll down to Enter Play Mode Settings. In a new project created from the Universal 3D template, “When entering Play Mode” is set to Reload Scene only. That means pressing Play reloads the scene but not your scripts:

Leave this setting at its default and use the following script to see how it affects a static field:
- Create a script the same way as in the previous section and name it
PlayCounter. The file name must match the class name in the code. - Replace its whole content with the code below and save.
- Drag
PlayCounteronto the Cube. - Open the Console window from Window > General > Console. The messages that Unity prints with
Debug.Logappear there. - Press Play, read the message in the Console, and press Play again to stop.
- Press Play once more and read the second message.
1using UnityEngine;
2
3public class PlayCounter : MonoBehaviour
4{
5 static int s_StaticCount;
6 int m_InstanceCount;
7
8 void Start()
9 {
10 s_StaticCount++;
11 m_InstanceCount++;
12 Debug.Log($"static: {s_StaticCount}, instance: {m_InstanceCount}");
13 }
14}
The first Play prints static: 1, instance: 1, and the second prints static: 2, instance: 1. m_InstanceCount lives on the Cube, so it starts from 0 every time Play reloads the scene. s_StaticCount does not belong to any object, and because Unity does not reload scripts, it keeps the 1 from the previous Play:

The Console has “Clear on Play” turned on by default. It clears the previous messages every time you press Play, so you normally see only the latest line. To see both messages at once, as in the screenshot above, click the arrow to the right of “Clear” at the top left of the Console and clear the “Clear on Play” check mark:

To make a static value return to its initial value on every Play, use Unity’s [AutoStaticsCleanup]. It is an attribute: a marker in square brackets that you write on the line above a field. Change PlayCounter.cs in three places so that Unity resets the static value every time you enter Play Mode:
- Add
using Unity.Scripting.LifecycleManagement;as the first line, so the code can find the attribute. - Add
partialbeforeclass. Unity generates an extra piece of code for the class that resets the value, andpartiallets the two pieces combine into one class. - Add
[AutoStaticsCleanup]on the line above the static field.
The whole file now looks like this:
1using Unity.Scripting.LifecycleManagement;
2using UnityEngine;
3
4public partial class PlayCounter : MonoBehaviour
5{
6 [AutoStaticsCleanup]
7 static int s_StaticCount;
8 int m_InstanceCount;
9
10 void Start()
11 {
12 s_StaticCount++;
13 m_InstanceCount++;
14 Debug.Log($"static: {s_StaticCount}, instance: {m_InstanceCount}");
15 }
16}
Save and press Play twice in a row. Both Plays print static: 1, instance: 1:

If you forget partial, the script fails to compile and the Console shows a red error. (4,14) means the problem is on line 4, the class line:
1PlayCounter.cs(4,14): error CS0260: Missing partial modifier on declaration of type 'PlayCounter'; another partial declaration of this type exists
In the Console, this red line starts with the full path of the script:

Add partial before class and save, and the error disappears.
The other option is to change “When entering Play Mode” to Reload Code and Scene. Every Play then reloads your scripts, and static fields return to 1 even without the attribute. The cost is a longer wait after you press Play. I measured three times in the same practice project: Reload Code and Scene took about 2.5 seconds each time, and the default Reload Scene only took about 0.07 seconds. This article therefore keeps the default and uses [AutoStaticsCleanup] for the static fields that need to reset.
[AutoStaticsCleanup] has other limits. For example, it can’t be used when the class has a static constructor, and you use [NoAutoStaticsCleanup] when a value must survive across Plays. These are covered in Preparing for Unity 7.
Check which C# syntax you can use
Each C# version adds new ways to write code. For example, C# 12 lets you create an array with int[] a = [1, 2, 3];. The manual for Unity 6 says C# 9.0. Starting with 7000.0.0a22, Unity 7 compiles scripts with .NET 10 and C# 14. .NET is the base library that C# programs use. However, the official release notes also say this applies only to supported platforms and that other platforms stay on C# 9. They don’t list which platforms those are.
In a Windows project on 7000.0.0a23, I tested one representative syntax from each C# version, and all of them compiled:
| C# version | Syntax | Code | Result |
|---|---|---|---|
| 10 | file-scoped namespace | namespace Probe; |
Compiles |
| 11 | raw string literal | var s = """abc"""; |
Compiles |
| 12 | collection expression | int[] a = [1, 2, 3]; |
Compiles |
| 12 | primary constructor for a class | class P(int x) |
Compiles |
| 13 | params with ReadOnlySpan |
Sum(params ReadOnlySpan<int> values) |
Compiles |
| 14 | field keyword |
public int X { get => field; set => field = value; } |
Compiles |
| 14 | extension members | extension(string s) { public int Len => s.Length; } |
Compiles |
Scripts in the Editor can use this syntax directly. When you build a player, Unity has two ways to handle C#, called scripting backends: CoreCLR runs C# on .NET directly, and IL2CPP converts C# to C++ and then compiles it. I put all seven samples into one script, built a Windows player with each backend, and ran it:
| Backend | Result |
|---|---|
| CoreCLR | The build succeeded, and the player printed correct results for all seven samples |
| IL2CPP | The build failed because Unity couldn’t find the Visual Studio C++ build tools |
Because IL2CPP compiles C++, it needs Visual Studio 2022 or later with the C++ build tools and a Windows SDK. My machine doesn’t have them, so I couldn’t test whether IL2CPP compiles C# 14 syntax. The release notes don’t list the supported platforms, so before you switch to IL2CPP or build for another platform, build once and check that your scripts compile.
VS Code doesn’t show red squiggles for this syntax either. I installed the Unity extension by following Set up Unity with VS Code or Cursor and opened the project folder, and none of the seven samples showed an error. The first time you open a new project, the status bar at the bottom of VS Code may show “Project load blocked” or “2 projects unavailable”. Code completion doesn’t work yet, and clicking the message opens C# Doctor, which says it can’t find a file under Library\MSBuild. This happened in both Unity 7 projects I tried. Build the .slnx file in the project root once from the VS Code terminal, then click “Retry project detection” in C# Doctor:
1dotnet build <project name>.slnx
Debugging with breakpoints works too. In the Run and Debug view on the left of VS Code, choose “Attach to Unity” and click the green triangle next to it to connect to the Editor, set a breakpoint in Start, and press Play. Execution stops on that line. Unity compiles scripts in Release mode by default, so some variables show “Cannot obtain value” when it stops. Click the bug icon at the bottom right of the Unity window, choose “Switch to debug mode”, wait for Unity to recompile, and press Play again. Now every variable shows its value.
Test notes
I tested on an empty project that I created with -createProject in Unity 7000.0.0a23 on Windows 11. For every script, I put it in Assets, opened the project once with Unity.exe -batchmode -nographics -quit -projectPath <project> so Unity would compile it, and judged the result from the log and the exit code. Batchmode runs the same Unity Editor program in the background without opening a window.
- C# syntax: I put in one script at a time, and all seven exited with code 0 and a log entry for compiling
Assembly-CSharp.dll. To confirm the test really compiles, I also wrote a script that assigns a string to anint. It exited with code 1, and the log showserror CS0029: Cannot implicitly convert type 'string' to 'int'and “Scripts have compiler errors.” - C# version setting: in the project,
Library/MSBuild/UnityProps/Common/TargetFramework.propssets both the Editor and the runtime tonet10.0andlatest, wherelatestmeans the newest C# version the compiler supports. The project file for scripts isAssets/Assembly-CSharp.gen.csproj, and the project root has noAssembly-CSharp.csproj. - Project structure: the root of a new project has
global.json,Main.EntryPoint.csproj,NuGet.config,<project name>.slnx, and a.vscodefolder.global.jsonpins .NET SDK 10.0.303 and Unity.Sdk 1.0.138. [AutoStaticsCleanup]: the type isUnity.Scripting.LifecycleManagement.AutoStaticsCleanupAttribute. Withoutpartial, the build exited with code 1 and the log showsCS0260, with no messages that start withUAL. Withpartial, it exited with code 0.- Editor test: I opened the Editor on a project created from the Universal 3D template, created a new scene from the Basic (URP) scene template, and followed the steps in this article to create Spinner and PlayCounter, with code identical to the code here. “When entering Play Mode” was Reload Scene only. I created the Cube with the GameObject > 3D Object > Cube menu command and attached the scripts from code, not by dragging with the mouse.
- Wait time: I recorded
EditorApplication.timeSinceStartupwhen I pressed Play and again at the next Editor update after entering Play Mode, then subtracted the two. Reload Code and Scene took 2.498, 2.533, and 2.577 seconds over three runs, and Reload Scene only took 0.080, 0.072, and 0.070 seconds. - Windows build: in a project created from the Universal 3D template, I added one script with all seven samples and called
BuildPipeline.BuildPlayerin batchmode to build a 64-bit Windows player. The CoreCLR build succeeded in 2 minutes 12 seconds, and the player printed the results of all seven samples to its log with the runtime.NET 10.0.10-dev. The IL2CPP build failed after 42 seconds withUnable to detect any compatible Visual Studio installation!, asking for the C++ build tools of Visual Studio 2022 or later and Windows SDK 10.0.19041.0 or later. - VS Code: VS Code 1.148.0, Unity extension 1.3.2 (which also installs C# Dev Kit 11.12.6 and C# 11.10.7), the project’s Visual Studio Editor package 2.0.29, and .NET SDK 10.0.404. I installed the extensions into a separate folder so my usual VS Code setup stayed unchanged. On a new project, C# Doctor reported
The input assembly does not exist, and runningdotnet buildfixed it. In Release mode, some variables at the breakpoint showedCannot obtain value of the local variable or argument because it is not available at this instruction pointer, possibly because it has been optimized away.After switching to Debug mode, all of them showed values. The debugger stayed attached while Unity recompiled after the mode switch. - In the empty project,
EditorSettings.assethasm_EnterPlayModeOptionsEnabled: 1andm_EnterPlayModeOptions: 1, which means pressing Play does not reload code.
Summary
A new Unity 7 project doesn’t reload scripts when you press Play, so static fields keep their values from the last run, and adding [AutoStaticsCleanup] and partial to the class makes every Play start from the initial values. Scripts can use C# 14 syntax in the Editor, in VS Code, and in a Windows player built with CoreCLR. Before you switch to IL2CPP or build for another platform, build once and check that your scripts compile.


