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.
- Check
.meta files before you finish. When you create, move, rename or delete
scripts or assets outside the Editor, always move a file together with its .meta
(a new .meta means a new GUID and broken references). Then run
python scripts/check_unity_project.py <project-dir> (--json for machine-readable
output), fix every ERROR (duplicate or malformed GUIDs, files moved without their
.meta, missing script references) and re-run until it exits 0. A missing .meta on a
brand-new file is only a warning; Unity creates it on the next import. Run the script
path relative to this skill directory, or resolve the installed skill path first. It
needs Python 3.10+ and nothing else, reads only text-serialized assets, and does not
replace opening the project in Unity.
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. Setting only the
script's enabled = false does not stop them.
- Obsolete warnings on
FindObjectOfType / FindObjectsOfType — Unity 6 replaced them.
Use FindFirstObjectByType (old behaviour), FindAnyObjectByType (faster, any match) or
FindObjectsByType(FindObjectsSortMode.None); all are slow, so cache the result.
- An
async method keeps running after its object is destroyed — await is not tied to
the GameObject the way a coroutine is. Pass destroyCancellationToken to the
Awaitable waits (they then throw OperationCanceledException), and never await the same
Awaitable instance twice: instances are pooled.
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, advanced coroutine patterns (custom
CustomYieldInstruction, stopping by handle, WaitUntil/WaitWhile) and the Awaitable
equivalents of coroutine waits, read references/lifecycle-and-coroutines.md.
scripts/check_unity_project.py — read-only .meta/GUID and missing-script checker;
--help lists every check and the exit codes.
- Primary docs: Unity Manual "Event function execution order"
(
https://docs.unity3d.com/Manual/execution-order.html), ScriptReference/MonoBehaviour,
and the Manual page "Asynchronous programming with the Awaitable class".
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: >4 Write Unity 6.3 LTS C# gameplay scripts: the MonoBehaviour lifecycle5 (Awake/OnEnable/Start/Update/FixedUpdate/LateUpdate), GameObject and component6 access, coroutines, and Inspector serialization. Use when creating or editing .cs7 scripts in a Unity project, or when the user mentions MonoBehaviour, Start/Update,8 GetComponent, SerializeField, coroutines, or "Unity script".9metadata:10 source: https://skillmd.com/skills/junmystery/unity-csharp-scripting11---1213# Unity C# Scripting (MonoBehaviour)1415Write correct, idiomatic gameplay scripts in Unity 6. Get the lifecycle, component16access, serialization, and coroutines right so behaviour is deterministic and the17Inspector stays useful. Targets **Unity 6.3 LTS (6000.3)**, C# / .NET Standard 2.1.1819## When to use2021- Use when authoring or fixing a `MonoBehaviour`: choosing the right lifecycle callback,22 reading/caching components, exposing fields to the Inspector, or running timed logic23 with coroutines.24- Use when the project has `*.cs` files, an `Assembly-CSharp` or `*.asmdef`, and a25 `ProjectSettings/` folder.2627**When *not* to use:** moving rigidbodies / collision response → `unity-physics`; reading28player input → `unity-input-system`; shared data assets / config → `unity-scriptableobjects`;29Animator parameters → `unity-animation`. This skill owns the *script lifecycle and C#30plumbing*, not those subsystems.3132## Core workflow33341. **Pick the callback by purpose, not habit.** `Awake` (cache references, runs once on35 load), `OnEnable` (subscribe to events), `Start` (init that depends on other objects'36 `Awake`), `Update` (per-frame logic/input polling), `FixedUpdate` (physics), `LateUpdate`37 (camera follow after movement), `OnDisable`/`OnDestroy` (unsubscribe/cleanup).382. **Cache component lookups in `Awake`** — never call `GetComponent` every frame.393. **Expose tunables with `[SerializeField] private`**, not public fields, so other code40 can't mutate them but designers can edit them in the Inspector.414. **Scale per-frame values by `Time.deltaTime`** in `Update` (and `Time.fixedDeltaTime`42 semantics are automatic in `FixedUpdate`).435. **Use coroutines for time-sequenced logic** (delays, tweens, "do X then wait then Y");44 start them with `StartCoroutine` and stop them deterministically.456. **Verify in Play mode**: check the Console for null-reference exceptions, confirm values46 in the Inspector update as expected, and watch the Profiler if `Update` is hot.477. **Check `.meta` files before you finish.** When you create, move, rename or delete48 scripts or assets outside the Editor, always move a file together with its `.meta`49 (a new `.meta` means a new GUID and broken references). Then run50 `python scripts/check_unity_project.py <project-dir>` (`--json` for machine-readable51 output), fix every `ERROR` (duplicate or malformed GUIDs, files moved without their52 `.meta`, missing script references) and re-run until it exits 0. A missing `.meta` on a53 brand-new file is only a warning; Unity creates it on the next import. Run the script54 path relative to this skill directory, or resolve the installed skill path first. It55 needs Python 3.10+ and nothing else, reads only text-serialized assets, and does not56 replace opening the project in Unity.5758## Patterns5960### 1. Lifecycle + cached components (the canonical skeleton)6162```csharp63using UnityEngine;6465[RequireComponent(typeof(Rigidbody))] // auto-adds the dependency, prevents null refs66public class PlayerController : MonoBehaviour67{68 [SerializeField] private float moveSpeed = 6f; // editable in Inspector, private in code69 private Rigidbody _rb; // cached, not fetched per frame7071 private void Awake() => _rb = GetComponent<Rigidbody>(); // cache once on load7273 private void Update()74 {75 // Per-frame, non-physics work. Scale by deltaTime so it is frame-rate independent.76 transform.Rotate(0f, 90f * Time.deltaTime, 0f);77 }7879 private void FixedUpdate()80 {81 // Physics work belongs here (fixed timestep). See the unity-physics skill.82 _rb.MovePosition(_rb.position + transform.forward * moveSpeed * Time.fixedDeltaTime);83 }84}85```8687### 2. Safe component access with `TryGetComponent`8889```csharp90// Avoids allocating a null and is clearer than GetComponent + null check.91if (other.TryGetComponent<Health>(out var health))92 health.Apply(-10);93```9495### 3. Serialization that shows up correctly in the Inspector9697```csharp98[SerializeField, Range(0f, 1f)] private float volume = 0.8f; // slider99[SerializeField] private string playerName = "Hero"; // private but serialized100101[System.Serializable] // REQUIRED for a plain class to serialize/show102public class Stats { public int hp = 100; public int mana = 50; }103104[SerializeField] private Stats stats = new(); // nested struct-like data in the Inspector105```106107### 4. Coroutines for time-sequenced logic108109```csharp110private void Start() => StartCoroutine(FlashThenHide());111112private System.Collections.IEnumerator FlashThenHide()113{114 yield return new WaitForSeconds(0.5f); // wait half a second of game time115 GetComponent<Renderer>().enabled = false;116 yield return null; // resume next frame117}118```119120## Pitfalls121122- **`GetComponent` in `Update`** — it searches every frame and tanks performance. Cache the123 reference in `Awake`/`Start`.124- **Physics in `Update`** — moving a `Rigidbody` with forces or `MovePosition` outside125 `FixedUpdate` causes jitter and timestep-dependent behaviour. Read input in `Update`,126 apply physics in `FixedUpdate`.127- **Relying on `Start` order across objects** — `Start` runs after *all* `Awake`s, but order128 among `Start`s is undefined. Do cross-object wiring in `Start`, self-setup in `Awake`.129- **`public` fields just to show them in the Inspector** — that also lets any script mutate130 them. Use `[SerializeField] private` instead.131- **`gameObject.tag == "Enemy"`** allocates a string and is slower; use132 `gameObject.CompareTag("Enemy")`.133- **Coroutines stop when the GameObject is disabled** — a disabled object's coroutines are134 killed; re-`StartCoroutine` in `OnEnable` if it must survive toggling. Setting only the135 script's `enabled = false` does *not* stop them.136- **Obsolete warnings on `FindObjectOfType` / `FindObjectsOfType`** — Unity 6 replaced them.137 Use `FindFirstObjectByType` (old behaviour), `FindAnyObjectByType` (faster, any match) or138 `FindObjectsByType(FindObjectsSortMode.None)`; all are slow, so cache the result.139- **An `async` method keeps running after its object is destroyed** — `await` is not tied to140 the GameObject the way a coroutine is. Pass `destroyCancellationToken` to the141 `Awaitable` waits (they then throw `OperationCanceledException`), and never await the same142 `Awaitable` instance twice: instances are pooled.143- **`Update` never runs before `Start`, but the *first* `Update` can run on the same144 frame as `Start`** — guard against not-yet-initialised fields if you split setup oddly.145146## References147148- For the full event-execution-order table, advanced coroutine patterns (custom149 `CustomYieldInstruction`, stopping by handle, `WaitUntil`/`WaitWhile`) and the `Awaitable`150 equivalents of coroutine waits, read `references/lifecycle-and-coroutines.md`.151- `scripts/check_unity_project.py` — read-only `.meta`/GUID and missing-script checker;152 `--help` lists every check and the exit codes.153- Primary docs: Unity Manual "Event function execution order"154 (`https://docs.unity3d.com/Manual/execution-order.html`), `ScriptReference/MonoBehaviour`,155 and the Manual page "Asynchronous programming with the Awaitable class".156157## Related skills158159- `unity-physics` — `Rigidbody`, collisions, and `FixedUpdate` motion.160- `unity-input-system` — reading player input into these scripts.161- `unity-scriptableobjects` — sharing data/config between scripts without singletons.