TExcelTAD
Home › Unity with C# › Field Notes: Scripting

Field Notes: Scripting

These are the scripting lessons Unity developers usually learn from a bug report or a profiler capture at 2 a.m. Most appeared earlier in the course; here they are in one place, each with the reason and the fix.

1. Never Find() in Update

GameObject.Find("Player"), FindFirstObjectByType<T>() and GetComponent<T>() search. In Update they search every frame, for every object running the script. Look things up once (in Awake/Start), or better, receive references through serialized fields, spawners or events.

csharp
// BAD: 300 enemies x 60 FPS = 18,000 scene searches per second
void Update() { var player = GameObject.Find("Player"); /* ... */ }

// GOOD
[SerializeField] Transform player;           // assigned by the spawner or the Inspector

The model counts the work: a scene search is a walk over all objects; a cached reference is one read.

csharp · try it yourself
using System;

int sceneObjects = 2000, enemies = 300, fps = 60;
long findPerSecond = (long)enemies * fps * sceneObjects / 2;   // on average, half the scene is scanned
long cachedPerSecond = (long)enemies * fps;                     // one field read each

Console.WriteLine(
quot;Find in Update : {findPerSecond,12:N0} object checks per second"); Console.WriteLine(
quot;cached field : {cachedPerSecond,12:N0} reads per second"); Console.WriteLine(
quot;ratio : {findPerSecond / cachedPerSecond,12:N0}x");
Find in Update :   18,000,000 object checks per second
cached field   :       18,000 reads per second
ratio          :        1,000x

2. Cache components and other lookups

Cache GetComponent results, Shader.PropertyToID, Animator.StringToHash, layer masks and WaitForSeconds in fields. TryGetComponent is the right call when a component may be missing.

3. FixedUpdate is for physics only

Forces, velocities and MovePosition go in FixedUpdate. Input, timers, UI and non-physics movement go in Update. Reading one-frame input in FixedUpdate drops or doubles presses (why). Inside FixedUpdate, Time.deltaTime returns the fixed step, so code is portable between the two, but the logic isn't.

4. Don't move a Rigidbody with transform

Setting transform.position teleports a body past the physics engine: tunneling, broken contacts, jitter. Use linearVelocity, AddForce, or MovePosition for kinematic bodies. And remember the Unity 6 names: linearVelocity, linearDamping.

5. Renaming serialized fields loses data

Serialized values are stored by field name. Rename with [FormerlySerializedAs("oldName")] and keep it until every asset has been re-saved. Same for class names of MonoBehaviours: renaming the class without renaming the file (or vice versa) gives "The associated script can not be loaded". Rename both together, inside the IDE.

6. Destroyed is not null: watch for "fake null"

Destroy frees the native object; your C# reference stays. ==, != and if (obj) know that; ?., ?? and is null don't. (details)

7. Allocations in Update cause GC spikes

String concatenation, LINQ, new List<T>(), capturing lambdas, GetComponents arrays and Instantiate/Destroy per bullet all create garbage. Aim for 0 B GC Alloc per frame in the Profiler during normal gameplay. (details)

8. Unsubscribe from everything you subscribe to

+= in OnEnable, -= in OnDisable. Static events and ScriptableObject channels outlive scenes, so a missing -= keeps destroyed objects alive and receiving calls.

9. Don't compare floats with ==, and don't accumulate time in float forever

Floating-point errors add up. Mathf.Approximately(a, b) or a tolerance for comparisons; and long-running timers lose precision in float. A timer += Time.deltaTime field drifts over hours, and Time.time itself is a float whose resolution gets coarser the longer the game runs. The model accumulates a 60 FPS clock in float and in double:

csharp · try it yourself
using System;

float time = 0f;
double exact = 0.0;
const float frame = 1f / 60f;
foreach (int hours in new[] { 1, 24, 100 })
{
    long frames = (long)hours * 3600 * 60;
    time = 0f; exact = 0;
    for (long i = 0; i < frames; i++) { time += frame; exact += 1.0 / 60; }
    Console.WriteLine(
quot;after {hours,3} h: float clock {time,12:F2} s, real {exact,12:F2} s, error {time - exact,10:F2} s"); } float big = 1000000f; // about 11.5 days in seconds Console.WriteLine(
quot;1000000 + 1/60 == 1000000 in float? {big + frame == big}");
after   1 h: float clock      3597.21 s, real      3600.00 s, error      -2.79 s
after  24 h: float clock     83794.82 s, real     86400.00 s, error   -2605.18 s
after 100 h: float clock    418445.66 s, real    360000.00 s, error   58445.66 s
1000000 + 1/60 == 1000000 in float? True

After one hour the float clock is already almost 3 seconds off, and the error isn't even in one direction: depending on the clock's magnitude, each 1/60 s step is rounded down (the clock runs slow) or up (it runs fast). At a million seconds a frame's worth of time disappears entirely. For long sessions use Time.timeAsDouble (and Time.unscaledTimeAsDouble), keep timers relative (count down a float remaining time, reset per use), and never store "seconds since startup" in a float for days-long servers.

10. Lerp(a, b, k) per frame is frame-rate dependent

Use Mathf.Lerp(a, b, 1f - Mathf.Exp(-speed * Time.deltaTime)) or Vector3.SmoothDamp. (details)

11. Know your execution order assumptions

Unity doesn't promise which script's Awake runs first. Initialize yourself in Awake, touch others in Start. If you really need an order, [DefaultExecutionOrder], and write down why.

12. Static state survives more than you think

With Enter Play Mode Options (domain reload off, a big iteration speed win), static fields and static events keep their values between Play sessions. Reset them in a [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] method.

13. SendMessage and string-based APIs

SendMessage("TakeDamage"), Invoke("Spawn", 2f) and StartCoroutine("Name") are slow, fail silently on typos, and break with renames. Use interfaces, direct calls, Awaitable/coroutines started from a method.

Test yourself

Which line belongs in FixedUpdate?

  1. if (jump.WasPressedThisFrame()) jumpQueued = true;
  2. body.AddForce(move * thrust);
  3. label.text = score.ToString();
  4. camera.position = Vector3.Lerp(...)

Why can a game timer stored as float Time.time misbehave after many hours?

  1. Unity resets it
  2. A float has about 7 significant digits, so tiny per-frame increments get rounded
  3. Time.time is an int
  4. It stops when paused

You renamed a MonoBehaviour class but not its file. What happens?

  1. Nothing
  2. Unity can't match the script to components: 'The associated script can not be loaded'
  3. Unity renames the file
  4. Only the Inspector layout changes