Loading...
Loading...
Unity C# fundamental patterns including TryGetComponent, SerializeField, RequireComponent, and safe coding practices. Essential patterns for robust Unity development. Use PROACTIVELY for any Unity C# code to ensure best practices.
npx skill4agent add creator-hian/claude-code-plugins unity-csharp-fundamentalsTryGetComponentGetComponent// ❌ WRONG
Rigidbody rb = GetComponent<Rigidbody>();
rb.velocity = Vector3.zero; // NullReferenceException!
// ✅ CORRECT
Rigidbody rb;
if (TryGetComponent(out rb))
{
rb.velocity = Vector3.zero;
}
// ✅ Cache in Awake with validation
private Rigidbody mRb;
void Awake()
{
if (!TryGetComponent(out mRb))
{
Debug.LogError($"Missing Rigidbody on {gameObject.name}", this);
}
}// ❌ OBSOLETE - DON'T USE
GameManager manager = FindObjectOfType<GameManager>();
// ✅ CORRECT - Fastest (unordered)
GameManager manager = FindAnyObjectByType<GameManager>();
// ✅ CORRECT - Ordered
GameManager manager = FindFirstObjectByType<GameManager>();
// ✅ Multiple objects
Enemy[] enemies = FindObjectsByType<Enemy>(FindObjectsSortMode.None);// ❌ WRONG: Public field
public float speed;
// ✅ CORRECT: SerializeField + private
[SerializeField] private float mSpeed = 5f;
// ✅ With Inspector helpers
[SerializeField, Tooltip("Units/second"), Range(0f, 100f)]
private float mMoveSpeed = 5f;
public float Speed => mSpeed; // Read-only access[RequireComponent(typeof(Rigidbody))]
[DisallowMultipleComponent]
public class PhysicsObject : MonoBehaviour
{
private Rigidbody mRb;
void Awake()
{
TryGetComponent(out mRb); // Guaranteed to exist
}
}// ❌ WRONG: C# null operators don't work with Unity Objects
Transform target = mCached ?? FindTarget(); // Broken!
mEnemy?.TakeDamage(10); // May fail after Destroy
// ✅ CORRECT: Explicit null check
Transform target = mCached != null ? mCached : FindTarget();
if (mEnemy != null)
{
mEnemy.TakeDamage(10);
}void Awake() { /* 1. Self-init, cache components */ }
void OnEnable() { /* 2. Subscribe events */ }
void Start() { /* 3. Cross-object init */ }
void OnDisable() { /* 4. Unsubscribe events */ }
void OnDestroy() { /* 5. Final cleanup */ }Important: Unity's Mono/IL2CPP runtime lacks.IsExternalInitaccessor causes compile error CS0518.init
// ❌ COMPILE ERROR in Unity
public string Name { get; private init; }
// ✅ Use private set
public string Name { get; private set; }
// ✅ Or readonly field + property
private readonly string mName;
public string Name => mName;initrequired| Pattern | Rule |
|---|---|
| Component access | Always |
| Serialization | |
| Dependencies | Use |
| Null checks | Explicit |
| Caching | Get in |
| Events | Subscribe in |
| Global search | |
initrequired