iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Unity C# Scripts

Unity scripts: MonoBehaviour, lifecycle, GetComponent, coroutines, and the patterns that scale beyond the prototype.

Game dev — Unity scripting

EXAMPLE
// ===== A MonoBehaviour =====
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float speed = 5f;
    [SerializeField] private float jumpForce = 8f;

    private Rigidbody2D rb;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Start() { /* runs once after Awake */ }

    void Update()
    {
        // input + game logic each frame
        var x = Input.GetAxisRaw("Horizontal");
        if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);

        rb.velocity = new Vector2(x * speed, rb.velocity.y);
    }

    void FixedUpdate() { /* physics tick (default 50Hz) */ }

    void OnCollisionEnter2D(Collision2D c) { /* ... */ }
    void OnTriggerEnter2D(Collider2D c) { /* ... */ }

    bool IsGrounded() { /* raycast down + check */ return true; }
}

// ===== Lifecycle order =====
// Awake -> OnEnable -> Start -> Update (per frame) -> FixedUpdate (per physics tick)
// -> LateUpdate (after Update; cameras + follow logic)
// -> OnDestroy (on scene unload / Destroy())

// ===== Getting components =====
// GetComponent<T>() is the canonical way; cache in Awake (it is not free).
private SpriteRenderer sr;
void Awake() { sr = GetComponent<SpriteRenderer>(); }

// ===== Inspector + ScriptableObjects =====
// [SerializeField] private exposes a field in the Inspector while keeping it private.
// ScriptableObject for data assets (configs, item definitions):
[CreateAssetMenu(menuName = "Items/WeaponData")]
public class WeaponData : ScriptableObject
{
    public string displayName;
    public int damage;
    public float range;
}

// ===== Coroutines (lightweight async) =====
IEnumerator FadeOut(float duration)
{
    float t = 0;
    var sr = GetComponent<SpriteRenderer>();
    while (t < duration) {
        t += Time.deltaTime;
        var c = sr.color; c.a = 1 - t / duration; sr.color = c;
        yield return null;   // wait one frame
    }
    Destroy(gameObject);
}
// Start with StartCoroutine(FadeOut(1.0f));

// ===== Events =====
// UnityEvent for inspector-wireable events; C# events for code-only:
using UnityEngine.Events;
public UnityEvent onScored;

// In code:
public static event System.Action<int> OnLevelUp;
OnLevelUp?.Invoke(newLevel);

// ===== Avoid Update for things that do not need it =====
// Every Update on every script costs CPU; cache results, throttle, or use FixedUpdate.

// ===== Static vs instance =====
// Static services (audio, input rebinding) are tempting; lean on Singletons + DI sparingly.
// Prefer dependency injection through Inspector references + ScriptableObjects.

// ===== Build + scenes =====
// Scenes: gameplay levels; load with SceneManager.LoadScene
// Prefabs: reusable game objects; instantiate with Instantiate(prefab, pos, rot)
// Addressables: load assets by string id; better for download-on-demand

// ===== Patterns to internalise =====
// - Cache GetComponent in Awake
// - Use Time.deltaTime in Update for frame-rate independence
// - ScriptableObjects for shared data
// - Coroutines for timed sequences; jobs / async for heavy compute

// ===== Pitfalls =====
// - GetComponent every Update -> hot allocation + lookup
// - Modifying Transform directly inside FixedUpdate -> physics fights
// - Static singletons used as global state by another name
// - Heavy Find() / FindObjectOfType in Update

Why it matters

Unity scripts live in MonoBehaviour. Cache references in Awake, use Time.deltaTime for movement, lean on ScriptableObjects for data, and reach for Coroutines for timed effects. The big wins are caching + frame-rate independence + small focused components; the antipatterns are giant scripts and Find calls in Update.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// Common Unity callbacks:
//   Awake()       once, before Start, before Scene activated
//   Start()       once, after Awake, before first Update
//   Update()      every frame
//   FixedUpdate() physics tick (default 50 Hz)
//   OnEnable / OnDisable / OnDestroy
Try it Yourself »

Discussion

Loading…