Unity C# Scripting (MonoBehaviour)
Write correct, idiomatic gameplay scripts in Unity 6. Get the lifecycle, component
access, serialization, and coroutines right so behaviour is deterministic and the
Inspector stays useful. Targets Unity 6.3 LTS (6000.3), C# / .NET Standard 2.1.
When to use
- Use when authoring or fixing a
MonoBehaviour: choosing the right lifecycle callback,
reading/caching components, exposing fields to the Inspector, or running timed logic
with coroutines.
- Use when the project has
*.cs files, an Assembly-CSharp or *.asmdef, and a
ProjectSettings/ folder.
When not to use: moving rigidbodies / collision response → unity-physics; reading
player input → unity-input-system; shared data assets / config → unity-scriptableobjects;
Animator parameters → unity-animation. This skill owns the script lifecycle and C#
plumbing, not those subsystems.
Core workflow
- Pick the callback by purpose, not habit.
Awake (cache references, runs once on
load), OnEnable (subscribe to events), Start (init that depends on other objects'
Awake), Update (per-frame logic/input polling), FixedUpdate (physics), LateUpdate
(camera follow after movement), OnDisable/OnDestroy (unsubscribe/cleanup).
- Cache component lookups in
Awake — never call GetComponent every frame.
- Expose tunables with
[SerializeField] private, not public fields, so other code
can't mutate them but designers can edit them in the Inspector.
- Scale per-frame values by
Time.deltaTime in Update (and Time.fixedDeltaTime
semantics are automatic in FixedUpdate).
- Use coroutines for time-sequenced logic (delays, tweens, "do X then wait then Y");
start them with
StartCoroutine and stop them deterministically.
- Verify in Play mode: check the Console for null-reference exceptions, confirm values
in the Inspector update as expected, and watch the Profiler if
Update is hot.
Patterns
1. Lifecycle + cached components (the canonical skeleton)
using UnityEngine;
[RequireComponent(typeof(Rigidbody))] // auto-adds the dependency, prevents null refs
public class PlayerController : MonoBehaviour
{
[SerializeField] private float moveSpeed = 6f; // editable in Inspector, private in code
private Rigidbody _rb; // cached, not fetched per frame
private void Awake() => _rb = GetComponent<Rigidbody>(); // cache once on load
private void Update()
{
// Per-frame, non-physics work. Scale by deltaTime so it is frame-rate independent.
transform.Rotate(0f, 90f * Time.deltaTime, 0f);
}
private void FixedUpdate()
{
// Physics work belongs here (fixed timestep). See the unity-physics skill.
_rb.MovePosition(_rb.position + transform.forward * moveSpeed * Time.fixedDeltaTime);
}
}
2. Safe component access with TryGetComponent
// Avoids allocating a null and is clearer than GetComponent + null check.
if (other.TryGetComponent<Health>(out var health))
health.Apply(-10);
3. Serialization that shows up correctly in the Inspector
[SerializeField, Range(0f, 1f)] private float volume = 0.8f; // slider
[SerializeField] private string playerName = "Hero"; // private but serialized
[System.Serializable] // REQUIRED for a plain class to serialize/show
public class Stats { public int hp = 100; public int mana = 50; }
[SerializeField] private Stats stats = new(); // nested struct-like data in the Inspector
4. Coroutines for time-sequenced logic
private void Start() => StartCoroutine(FlashThenHide());
private System.Collections.IEnumerator FlashThenHide()
{
yield return new WaitForSeconds(0.5f); // wait half a second of game time
GetComponent<Renderer>().enabled = false;
yield return null; // resume next frame
}
Pitfalls
GetComponent in Update — it searches every frame and tanks performance. Cache the
reference in Awake/Start.
- Physics in
Update — moving a Rigidbody with forces or MovePosition outside
FixedUpdate causes jitter and timestep-dependent behaviour. Read input in Update,
apply physics in FixedUpdate.
- Relying on
Start order across objects — Start runs after all Awakes, but order
among Starts is undefined. Do cross-object wiring in Start, self-setup in Awake.
public fields just to show them in the Inspector — that also lets any script mutate
them. Use [SerializeField] private instead.
gameObject.tag == "Enemy" allocates a string and is slower; use
gameObject.CompareTag("Enemy").
- Coroutines stop when the GameObject is disabled — a disabled object's coroutines are
killed; re-
StartCoroutine in OnEnable if it must survive toggling.
Update never runs before Start, but the first Update can run on the same
frame as Start — guard against not-yet-initialised fields if you split setup oddly.
References
- For the full event-execution-order table and advanced coroutine patterns (custom
CustomYieldInstruction, stopping by handle, WaitUntil/WaitWhile), read
references/lifecycle-and-coroutines.md.
- Primary docs: Unity Manual "Event function execution order"
(
https://docs.unity3d.com/Manual/execution-order.html) and ScriptReference/MonoBehaviour.
Related skills
unity-physics — Rigidbody, collisions, and FixedUpdate motion.
unity-input-system — reading player input into these scripts.
unity-scriptableobjects — sharing data/config between scripts without singletons.
1---2name: unity-csharp-scripting3description: Write Unity 6.3 LTS C# gameplay scripts: the MonoBehaviour lifecycle (Awake/OnEnable/Start/Update/FixedUpdate/LateUpdate), GameObject and component access, coroutines, and Inspector serialization. Use when creating or editing .cs scripts in a Unity project, or when the user mentions MonoBehaviour, Start/Update, GetComponent, SerializeField, coroutines, or "Unity script".4---5
6# Unity C# Scripting (MonoBehaviour)
7
8Write correct, idiomatic gameplay scripts in Unity 6. Get the lifecycle, component
9access, serialization, and coroutines right so behaviour is deterministic and the
10Inspector stays useful. Targets **Unity 6.3 LTS (6000.3)**, C# / .NET Standard 2.1.
11
12## When to use
13
14- Use when authoring or fixing a `MonoBehaviour`: choosing the right lifecycle callback,
15 reading/caching components, exposing fields to the Inspector, or running timed logic
16 with coroutines.
17- Use when the project has `*.cs` files, an `Assembly-CSharp` or `*.asmdef`, and a
18 `ProjectSettings/` folder.
19
20**When *not* to use:** moving rigidbodies / collision response → `unity-physics`; reading
21player input → `unity-input-system`; shared data assets / config → `unity-scriptableobjects`;
22Animator parameters → `unity-animation`. This skill owns the *script lifecycle and C#
23plumbing*, not those subsystems.
24
25## Core workflow
26
271. **Pick the callback by purpose, not habit.** `Awake` (cache references, runs once on
28 load), `OnEnable` (subscribe to events), `Start` (init that depends on other objects'
29 `Awake`), `Update` (per-frame logic/input polling), `FixedUpdate` (physics), `LateUpdate`
30 (camera follow after movement), `OnDisable`/`OnDestroy` (unsubscribe/cleanup).
312. **Cache component lookups in `Awake`** — never call `GetComponent` every frame.
323. **Expose tunables with `[SerializeField] private`**, not public fields, so other code
33 can't mutate them but designers can edit them in the Inspector.
344. **Scale per-frame values by `Time.deltaTime`** in `Update` (and `Time.fixedDeltaTime`
35 semantics are automatic in `FixedUpdate`).
365. **Use coroutines for time-sequenced logic** (delays, tweens, "do X then wait then Y");
37 start them with `StartCoroutine` and stop them deterministically.
386. **Verify in Play mode**: check the Console for null-reference exceptions, confirm values
39 in the Inspector update as expected, and watch the Profiler if `Update` is hot.
40
41## Patterns
42
43### 1. Lifecycle + cached components (the canonical skeleton)
44
45```csharp
46using UnityEngine;
47
48[RequireComponent(typeof(Rigidbody))] // auto-adds the dependency, prevents null refs
49public class PlayerController : MonoBehaviour
50{
51 [SerializeField] private float moveSpeed = 6f; // editable in Inspector, private in code
52 private Rigidbody _rb; // cached, not fetched per frame
53
54 private void Awake() => _rb = GetComponent<Rigidbody>(); // cache once on load
55
56 private void Update()
57 {
58 // Per-frame, non-physics work. Scale by deltaTime so it is frame-rate independent.
59 transform.Rotate(0f, 90f * Time.deltaTime, 0f);
60 }
61
62 private void FixedUpdate()
63 {
64 // Physics work belongs here (fixed timestep). See the unity-physics skill.
65 _rb.MovePosition(_rb.position + transform.forward * moveSpeed * Time.fixedDeltaTime);
66 }
67}
68```
69
70### 2. Safe component access with `TryGetComponent`
71
72```csharp
73// Avoids allocating a null and is clearer than GetComponent + null check.
74if (other.TryGetComponent<Health>(out var health))
75 health.Apply(-10);
76```
77
78### 3. Serialization that shows up correctly in the Inspector
79
80```csharp
81[SerializeField, Range(0f, 1f)] private float volume = 0.8f; // slider
82[SerializeField] private string playerName = "Hero"; // private but serialized
83
84[System.Serializable] // REQUIRED for a plain class to serialize/show
85public class Stats { public int hp = 100; public int mana = 50; }
86
87[SerializeField] private Stats stats = new(); // nested struct-like data in the Inspector
88```
89
90### 4. Coroutines for time-sequenced logic
91
92```csharp
93private void Start() => StartCoroutine(FlashThenHide());
94
95private System.Collections.IEnumerator FlashThenHide()
96{
97 yield return new WaitForSeconds(0.5f); // wait half a second of game time
98 GetComponent<Renderer>().enabled = false;
99 yield return null; // resume next frame
100}
101```
102
103## Pitfalls
104
105- **`GetComponent` in `Update`** — it searches every frame and tanks performance. Cache the
106 reference in `Awake`/`Start`.
107- **Physics in `Update`** — moving a `Rigidbody` with forces or `MovePosition` outside
108 `FixedUpdate` causes jitter and timestep-dependent behaviour. Read input in `Update`,
109 apply physics in `FixedUpdate`.
110- **Relying on `Start` order across objects** — `Start` runs after *all* `Awake`s, but order
111 among `Start`s is undefined. Do cross-object wiring in `Start`, self-setup in `Awake`.
112- **`public` fields just to show them in the Inspector** — that also lets any script mutate
113 them. Use `[SerializeField] private` instead.
114- **`gameObject.tag == "Enemy"`** allocates a string and is slower; use
115 `gameObject.CompareTag("Enemy")`.
116- **Coroutines stop when the GameObject is disabled** — a disabled object's coroutines are
117 killed; re-`StartCoroutine` in `OnEnable` if it must survive toggling.
118- **`Update` never runs before `Start`, but the *first* `Update` can run on the same
119 frame as `Start`** — guard against not-yet-initialised fields if you split setup oddly.
120
121## References
122
123- For the full event-execution-order table and advanced coroutine patterns (custom
124 `CustomYieldInstruction`, stopping by handle, `WaitUntil`/`WaitWhile`), read
125 `references/lifecycle-and-coroutines.md`.
126- Primary docs: Unity Manual "Event function execution order"
127 (`https://docs.unity3d.com/Manual/execution-order.html`) and `ScriptReference/MonoBehaviour`.
128
129## Related skills
130
131- `unity-physics` — `Rigidbody`, collisions, and `FixedUpdate` motion.
132- `unity-input-system` — reading player input into these scripts.
133- `unity-scriptableobjects` — sharing data/config between scripts without singletons.