unity-csharp-fundamentals
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.
Best use case
unity-csharp-fundamentals is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
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.
Teams using unity-csharp-fundamentals should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/unity-csharp-fundamentals/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How unity-csharp-fundamentals Compares
| Feature / Agent | unity-csharp-fundamentals | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
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.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Unity C# Fundamentals - Essential Coding Patterns
## Overview
Core Unity C# patterns for safe, maintainable code. Not optimizations but **fundamental practices**.
**Foundation Required**: C# basics, Unity MonoBehaviour lifecycle
**Core Topics**: TryGetComponent, SerializeField, RequireComponent, Null-safe patterns, Lifecycle management
## Essential Patterns
### TryGetComponent (Required)
**Always use `TryGetComponent` instead of `GetComponent`**:
```csharp
// ❌ 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);
}
}
```
### Global Object Search (Unity 2023.1+)
```csharp
// ❌ 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);
```
### SerializeField Pattern
```csharp
// ❌ 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
```csharp
[RequireComponent(typeof(Rigidbody))]
[DisallowMultipleComponent]
public class PhysicsObject : MonoBehaviour
{
private Rigidbody mRb;
void Awake()
{
TryGetComponent(out mRb); // Guaranteed to exist
}
}
```
### Unity Null Safety
```csharp
// ❌ 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);
}
```
### Lifecycle Order
```csharp
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 */ }
```
## Unity C# 9.0 Limitations
> **Important**: Unity's Mono/IL2CPP runtime lacks `IsExternalInit`.
> `init` accessor causes compile error CS0518.
```csharp
// ❌ 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;
```
**Available**: Pattern matching, switch expressions, covariant returns
**NOT Available**: `init`, `required` (C# 11)
## Quick Reference
| Pattern | Rule |
|---------|------|
| Component access | Always `TryGetComponent`, never bare `GetComponent` |
| Serialization | `[SerializeField] private`, not `public` |
| Dependencies | Use `[RequireComponent]` for guaranteed components |
| Null checks | Explicit `!= null`, not `??` or `?.` |
| Caching | Get in `Awake`, reuse everywhere |
| Events | Subscribe in `OnEnable`, unsubscribe in `OnDisable` |
| Global search | `FindAnyObjectByType` (fastest), not `FindObjectOfType` |
## Reference Documentation
### [Component Access Patterns](references/component-access.md)
- TryGetComponent variations and interface-based access
- GetComponentInChildren/Parent patterns
- Allocation-free multiple component access
- Caching strategies and performance comparisons
### [Attributes and Patterns](references/attributes-patterns.md)
- Complete serialization attribute reference
- Inspector customization (Header, Tooltip, Range)
- Execution order control
- Conditional compilation
### [Language Limitations](references/language-limitations.md)
- `init` accessor alternatives with code examples
- Records in Unity (limitations and workarounds)
- `required` modifier alternatives
- Available C# 9.0 features in UnityRelated Skills
unity-vcontainer
VContainer dependency injection expert specializing in IoC container configuration, lifecycle management, and Unity-optimized DI patterns. Masters dependency resolution, scoped containers, and testable architecture design. Use PROACTIVELY for VContainer setup, service registration, or SOLID principle implementation.
unity-unitask
UniTask library expert specializing in allocation-free async/await patterns, coroutine migration, and Unity-optimized asynchronous programming. Masters UniTask performance optimizations, cancellation handling, and memory-efficient async operations. Use PROACTIVELY for UniTask implementation, async optimization, or coroutine replacement.
unity-unirx
UniRx (Reactive Extensions) library expert for legacy Unity projects. Specializes in UniRx-specific patterns, Observable streams, and ReactiveProperty. Use for maintaining existing UniRx codebases. For new projects, use unity-r3 skill instead.
unity-ui
Build and optimize Unity UI with UI Toolkit and UGUI. Masters responsive layouts, event systems, and performance optimization. Use for UI implementation, Canvas optimization, or cross-platform UI challenges.
unity-textmeshpro
TextMeshPro (TMPro) expert for Unity text rendering with advanced typography, performance optimization, and professional text effects. Masters font asset creation, dynamic fonts, rich text formatting, material presets, and text mesh optimization. Use PROACTIVELY for text rendering, font management, localization text, UI text performance, or text effects implementation.
unity-testrunner
Unity Test Framework CLI automation and test writing patterns. Masters batchmode execution, NUnit assertions, EditMode/PlayMode testing, and TDD workflows. Use PROACTIVELY for test automation, CI/CD pipelines, or test-driven development in Unity.
unity-r3
R3 (Reactive Extensions) library expert specializing in modern reactive programming patterns, event-driven architectures, and Observable streams. Masters R3-specific features, async enumerable integration, and Unity-optimized reactive patterns. Use PROACTIVELY for R3 implementation, reactive programming, or MVVM/MVP architecture.
unity-performance
Optimize Unity game performance through profiling, draw call reduction, and resource management. Masters batching, LOD, occlusion culling, and mobile optimization. Use for performance bottlenecks, frame rate issues, or optimization strategies.
unity-networking
Implement multiplayer games with Unity Netcode, Mirror, or Photon. Masters client-server architecture, state synchronization, and lag compensation. Use for multiplayer features, networking issues, or real-time synchronization.
unity-mobile
Optimize Unity games for mobile platforms with IL2CPP, platform-specific code, and memory management. Masters iOS/Android deployment, app size reduction, and battery optimization. Use for mobile builds, platform issues, or device-specific optimization.
unity-collection-pool
Unity Collection Pool expert for GC-free collection management using ListPool, DictionaryPool, HashSetPool, and ObjectPool. Masters memory optimization, pool sizing, and allocation-free patterns. Use PROACTIVELY for collection allocations, GC pressure reduction, temporary list/dictionary usage, or performance-critical code paths.
unity-async
Handle Unity's asynchronous programming patterns including coroutines, async/await, and Job System. Masters Unity's main thread restrictions and threading models. Use when guidance needed on Unity async operations, coroutine optimization, or parallel processing in Unity context.