Skip to content

MustafaKucukcoskun/Refine-agent-kit / shared/.agent/skills/unity-developer

unity-developer

Unverified

Unity C# patterns — MonoBehaviour lifecycle, ScriptableObject architecture, Input System, physics, coroutines vs async, object pooling, editor scripting, performance. Use when building Unity games.

Unity Developer Patterns

Production-ready Unity C# patterns. Component-based, performance-aware.


1. MonoBehaviour Lifecycle

Initialization:
  Awake()           → Called once when object is created (before Start)
  OnEnable()        → Called when object becomes active
  Start()           → Called once before first Update (after Awake)

Game Loop:
  FixedUpdate()     → Physics (fixed timestep, default 0.02s)
  Update()          → Game logic (every frame, variable timestep)
  LateUpdate()      → Camera follow, post-processing (after all Updates)

Cleanup:
  OnDisable()       → When object becomes inactive
  OnDestroy()       → When object is destroyed

Rules

UseFor
Awake()Self-initialization, GetComponent caching
Start()Cross-object references (other objects' Awake ran)
FixedUpdate()Physics: Rigidbody forces, raycasts
Update()Input polling, game logic, animations
LateUpdate()Camera tracking, UI updates after movement
public class PlayerController : MonoBehaviour
{
    private Rigidbody _rb;
    private PlayerInput _input;

    void Awake()
    {
        // Cache components in Awake — runs before Start
        _rb = GetComponent<Rigidbody>();
        _input = GetComponent<PlayerInput>();
    }

    void FixedUpdate()
    {
        // Physics in FixedUpdate
        _rb.AddForce(moveDirection * speed);
    }

    void LateUpdate()
    {
        // Camera follows after all movement is done
        UpdateCameraPosition();
    }
}

2. ScriptableObject Architecture

Data Container

[CreateAssetMenu(fileName = "WeaponData", menuName = "Game/Weapon Data")]
public class WeaponData : ScriptableObject
{
    public string weaponName;
    public float damage;
    public float fireRate;
    public GameObject projectilePrefab;
}

Event Channel Pattern

[CreateAssetMenu(menuName = "Events/Void Event")]
public class VoidEventChannel : ScriptableObject
{
    private readonly HashSet<Action> _listeners = new();

    public void Register(Action listener) => _listeners.Add(listener);
    public void Unregister(Action listener) => _listeners.Remove(listener);

    public void Raise()
    {
        foreach (var listener in _listeners)
            listener?.Invoke();
    }
}
// Usage — decoupled communication
public class Player : MonoBehaviour
{
    [SerializeField] private VoidEventChannel onPlayerDeath;

    void Die() => onPlayerDeath.Raise();
}

public class GameUI : MonoBehaviour
{
    [SerializeField] private VoidEventChannel onPlayerDeath;

    void OnEnable() => onPlayerDeath.Register(ShowGameOver);
    void OnDisable() => onPlayerDeath.Unregister(ShowGameOver);
    void ShowGameOver() => gameOverPanel.SetActive(true);
}

3. Input System (New)

using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 5f;
    private Vector2 _moveInput;

    // Called by PlayerInput component (Send Messages / Invoke Events)
    public void OnMove(InputAction.CallbackContext ctx)
    {
        _moveInput = ctx.ReadValue<Vector2>();
    }

    void Update()
    {
        transform.Translate(new Vector3(_moveInput.x, 0, _moveInput.y) * moveSpeed * Time.deltaTime);
    }
}

4. Physics: Rigidbody vs CharacterController

FeatureRigidbodyCharacterController
Physics interactions✅ Full (gravity, collisions, forces)❌ Manual only
Slopes/StepsManual setup✅ Built-in (slopeLimit, stepOffset)
Best forPhysics-driven objects, vehiclesHumanoid characters, FPS
MovementAddForce / MovePositionMove / SimpleMove

5. Coroutine vs async/await

FeatureCoroutineasync/await
Unity lifecycle aware✅ Stops on destroy❌ Runs after destroy
Frame-based delays✅ yield return null❌ Needs wrapper
CancelableStop via StopCoroutineCancellationToken
Best forAnimations, sequencesI/O, HTTP, file ops
// Coroutine — animation sequence
IEnumerator FlashDamage()
{
    _renderer.material.color = Color.red;
    yield return new WaitForSeconds(0.1f);
    _renderer.material.color = _originalColor;
}

// async/await — web request
async Task<string> FetchLeaderboard(CancellationToken ct)
{
    using var request = UnityWebRequest.Get(url);
    await request.SendWebRequest().WithCancellation(ct);
    return request.downloadHandler.text;
}

6. Object Pooling

public class BulletPool : MonoBehaviour
{
    [SerializeField] private GameObject bulletPrefab;
    [SerializeField] private int poolSize = 20;
    private Queue<GameObject> _pool;

    void Awake()
    {
        _pool = new Queue<GameObject>();
        for (int i = 0; i < poolSize; i++)
        {
            var bullet = Instantiate(bulletPrefab, transform);
            bullet.SetActive(false);
            _pool.Enqueue(bullet);
        }
    }

    public GameObject Get(Vector3 position, Quaternion rotation)
    {
        var bullet = _pool.Count > 0 ? _pool.Dequeue() : Instantiate(bulletPrefab, transform);
        bullet.transform.SetPositionAndRotation(position, rotation);
        bullet.SetActive(true);
        return bullet;
    }

    public void Return(GameObject bullet)
    {
        bullet.SetActive(false);
        _pool.Enqueue(bullet);
    }
}

7. Editor Scripting

#if UNITY_EDITOR
using UnityEditor;

[CustomEditor(typeof(EnemySpawner))]
public class EnemySpawnerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        var spawner = (EnemySpawner)target;
        if (GUILayout.Button("Spawn Test Wave"))
            spawner.SpawnWave();
    }
}

// Menu item
public static class ToolsMenu
{
    [MenuItem("Tools/Clear Save Data")]
    static void ClearSaveData()
    {
        PlayerPrefs.DeleteAll();
        Debug.Log("Save data cleared");
    }
}
#endif

8. Performance

Update() Optimization

// ❌ Expensive in Update
void Update()
{
    var enemy = GameObject.FindWithTag("Enemy");    // Find every frame!
    var dist = Vector3.Distance(transform.position, enemy.transform.position);
}

// ✅ Cache + interval
private Transform _enemy;
private float _checkInterval = 0.5f;
private float _nextCheck;

void Start() => _enemy = GameObject.FindWithTag("Enemy").transform;

void Update()
{
    if (Time.time < _nextCheck) return;
    _nextCheck = Time.time + _checkInterval;
    var sqrDist = (transform.position - _enemy.position).sqrMagnitude; // No sqrt
}

Key Rules

❌ Avoid✅ Instead
Find* in UpdateCache in Awake/Start
Vector3.DistancesqrMagnitude (no sqrt)
Instantiate/DestroyObject pooling
LINQ in hot pathManual loops
GetComponent per frameCache reference
String concat in UIStringBuilder / TextMeshPro.SetText

Quick Reference

TaskPattern
InitAwake (self) → Start (cross-ref)
PhysicsFixedUpdate + Rigidbody
DataScriptableObject assets
EventsSO Event Channel (decoupled)
InputNew Input System + PlayerInput
PoolingQueue-based pool
UI updatesLateUpdate
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 192kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 192kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 192kUpdated Claude CodeCodexVerifiedInstall