0% found this document useful (0 votes)
16 views5 pages

CSharp Unity Cheatsheet

This cheat sheet provides a concise reference for C# programming in Unity, covering syntax, common mistakes, MonoBehaviour lifecycle, coroutines, and performance tips. It includes quick rules, types and variables, methods, operators, and debugging advice. The document serves as a practical guide for game developers, with key points on Unity's execution order and inspector attributes.

Uploaded by

bvpatel1242
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views5 pages

CSharp Unity Cheatsheet

This cheat sheet provides a concise reference for C# programming in Unity, covering syntax, common mistakes, MonoBehaviour lifecycle, coroutines, and performance tips. It includes quick rules, types and variables, methods, operators, and debugging advice. The document serves as a practical guide for game developers, with key points on Unity's execution order and inspector attributes.

Uploaded by

bvpatel1242
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C# for Unity — Cheat Sheet (Compact & Practical)

A focused reference for Unity game development: syntax, rules, common mistakes, MonoBehaviour lifecycle, coroutines, attributes,
and performance tips.

Quick rules & common gotchas


• C# is case-sensitive: PlayerHealth ≠ playerHealth.
• Every statement ends with a semicolon `;`.
• Use `f` for float literals (e.g., 5.0f).
• Use `==` for comparison, `=` for assignment.
• Prefer `var` only when the type is obvious; explicit types improve readability.
• Watch value vs reference types: structs are value types (copied), classes are reference types (by reference).
• Avoid allocations in Update (strings, LINQ, creating new objects) to reduce GC spikes.

Types & variables


// Common types
int score = 0;
float speed = 5.0f;
double large = 1.0;
bool isAlive = true;
string name = "Unity";
int[] arr = new int[3];
List<int> list = new List<int>() {1,2,3};
var inferred = 10; // inferred as int

Fields, properties & access modifiers


public class Player : MonoBehaviour {
public int health = 100; // editable in inspector (public)
[SerializeField] private int ammo; // editable in inspector (private shown)
private int secret; // hidden in inspector
public int Score { get; private set; } // property with private setter
public static Player Instance; // static reference (singleton caution)
}

Operators & control flow (essentials)


// Operators
a + b, a - b, a * b, a / b, a % b
a == b, a != b, a < b, a > b
&&, ||, !
?? (null-coalescing), ?. (null-conditional), => (lambda)
?: (ternary)

// Control flow
if(condition) { } else if { } else { }
switch(value) { case X: break; }

// Loops
for(int i=0;i<n;i++) { }
foreach(var item in collection) { }
while(condition) { }

Methods, delegates, lambdas


void Start() { } // Unity callback
int Add(int a, int b) { return a+b; }
Func<int,int> square = x => x*x; // lambda
Action onDeath; // delegate
event Action Died; // event

Classes, inheritance & OOP


// Inheritance & overrides
public abstract class Enemy {
public abstract void Act();
}
public class Zombie : Enemy {
public override void Act() { /*...*/ }
}

// Interface
public interface IDamageable {
void TakeDamage(int dmg);
}

// Sealed and new


public sealed class FinalClass { }
public class Sub : Base {
public new void Foo() { } // hides base method

Unity — MonoBehaviour lifecycle & execution order (key points)


Important: Awake is called before Start. OnEnable is called when object becomes active. Start runs before first frame but may be
delayed until end of frame for some cases. Use FixedUpdate for physics and Update for per-frame logic. (See Unity docs for full
order.)

Common MonoBehaviour callbacks (most used):


Awake() // initialization (called first)
OnEnable() // when enabled/activated
Start() // before first frame, after Awake
Update() // per-frame
LateUpdate() // after Update
FixedUpdate() // physics (fixed timestep)
OnTriggerEnter(Collider other)
OnCollisionEnter(Collision collision)
OnDisable()
OnDestroy()

Coroutines (Unity) — basics


// Coroutine example
IEnumerator Blink() {
while(true) {
yield return new WaitForSeconds(0.5f); // wait half second
// toggle something
}
}
StartCoroutine(Blink());
// Stop: StopCoroutine(Blink()) or StopAllCoroutines()

Unity attributes & inspector helpers


[SerializeField] private int value; // show private in inspector
[Header("Stats")] public int hp;
[Range(0,100)] public int percent;
[HideInInspector] public int hidden;
[RequireComponent(typeof(Rigidbody))] // auto-add component when script added
[ExecuteInEditMode] // run in editor
Common Unity API patterns & tips
// Getting components
var rb = GetComponent<Rigidbody>();
var cam = [Link]; // cached access recommended

// Instantiation
var go = Instantiate(prefab, position, rotation);

// Transform helpers
[Link] += [Link] * speed * [Link];

// Destroy
Destroy(go);
Destroy(go, 2f); // delayed

// Input
if([Link]([Link])) { /*...*/ }

Performance & GC tips (practical)


• Cache references (GetComponent, [Link]) — avoid calling every frame.
• Avoid allocations in Update: no new objects, avoid LINQ in hot paths.
• Use object pooling for frequently spawned/despawned items.
• Use FixedUpdate for physics changes; multiply by [Link] when needed.
• Prefer struct for very small value types, but be careful with copying costs.
• Mark fields [NonSerialized] or private if you don't need inspector exposure.

Debugging & common mistakes


• Misspelling Unity callbacks: 'update' != 'Update' (case matters).
• NullReferenceException: check object != null before using it.
• Using Find/FindObjectOfType in Update — expensive.
• Forgetting 'f' suffix on floats (5.0f).
• Integer division: 1/2 == 0 (use 1f/2f for floats).
• Leaving heavy math/allocations in Update.
• Misusing physics callbacks: use OnCollisionEnter for non-trigger colliders and OnTriggerEnter for triggers.

Useful snippets & one-liners


// Safe null invoke
Died?.Invoke();

// Null-coalescing assignment
player ??= FindObjectOfType<Player>();

// Property shorthand
public int Health { get; private set; } = 100;

// Extension method example


public static class TransformExt {
public static void Reset(this Transform t) {
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
}
}

Inspector attributes quick reference


Attribute Effect Use
[SerializeField] Show private field in inspector When you want private but editable

[Range(min,max)] Slider in inspector Numeric ranges

[Header("text")] Add header in inspector Organization

[HideInInspector] Hide public field in inspector Keep public access but hide

[RequireComponent(typeof(...))] Auto-add required component Ensure dependencies

References (selected official & authoritative sources)


• Unity Scripting API — MonoBehaviour & execution order (Unity Docs)
• Microsoft C# Language Reference (operators, types, keywords)
• Unity C# Style Guide (Unity resources)
• Unity Manual — Coroutines & attributes
• Best practice guides & common Unity mistakes articles
Compact Quick Reference (page 2)
— Lifecycle: Awake -> OnEnable -> Start -> Update -> LateUpdate -> OnDisable -> OnDestroy
— Physics: Use FixedUpdate; apply forces on Rigidbody in FixedUpdate
— Coroutines: StartCoroutine(), yield return new WaitForSeconds(x)
— Inspector: [SerializeField], public fields visible; use [Range], [Header], [Tooltip]
— Common errors: NullReferenceException, IndexOutOfRange, forgetting semicolon, wrong case on method name
— Use [Link] to make movement frame-rate independent
— Use GetComponent<T>() caching. Avoid GetComponent in Update.
— Use object pooling for repeated instantiate/destroy

Generated: C# for Unity — Cheat Sheet. Use as a compact reference during practice. For deep dives, consult Unity and Microsoft
official docs.

Common questions

Powered by AI

Awake is called when the script instance is being loaded, it is used for initialization tasks that happen regardless of the object being active or not. OnEnable is called just before Update when an object becomes active. Use Awake when you want initialization independent of object activation (like setting up references), and OnEnable for tasks that should run every time the object becomes active again (like resetting states or subscribing to events).

Null-conditional operators (e.g., ?. and ??) in C# provide a concise way to access members and avoid null reference exceptions. They check for null values before accessing a member or method, which prevents exceptions by returning null rather than attempting to dereference a null object. An example is using the ?. operator in `player?.Invoke()` to call a method on player only if player is not null, preventing runtime errors .

Object pooling improves performance by reusing instances of frequently created and destroyed objects, thereby reducing the overhead of memory allocation and garbage collection. In Unity, this is particularly beneficial in scenarios like spawning enemies or bullets, where frequent instantiation can lead to performance issues due to heavy load on the Garbage Collector. Object pooling minimizes this by keeping a pool of inactive objects that are activated and deactivated as needed .

Instantiating new objects and using LINQ in the Update method can lead to frequent memory allocations, causing garbage collection spikes that degrade performance. Strategies to mitigate these issues include object pooling for repeated object usage, caching results of expensive operations, and moving non-time-critical logic out of Update. Additionally, optimizing code outside of Update for repeated structures or frequently accessed data can help maintain performance .

The Start method is called before the first frame update, after all the Awake methods on scene objects have been called. It is generally used for initialization that only needs to happen once. Update is called once per frame, and is used for ongoing operations like checking input or time-based actions. Understanding these differences is crucial as using Start for repeated logic can lead to performance issues, while using Update for non-repeating initialization can delay logic execution unnecessarily .

Using explicit types in C# improves readability by clearly indicating the type of a variable at the point of its declaration, making the code more understandable and reducing potential type-related errors. On the other hand, 'var' allows for cleaner and shorter code but can obscure the declared type, potentially leading to misunderstandings among developers. Performance is identical in both cases, but clear understanding of a variable's type can prevent logic errors and bugs when rate conversion or method overloading might occur .

Using properties with a private setter in Unity helps maintain encapsulation by allowing controlled access to private fields. This approach prevents unauthorized modification of key variables while allowing safe read access through public properties. Code integrity is preserved as changes to properties can trigger specific logic within the setter, providing opportunities to safeguard against invalid state changes .

FixedUpdate is called at a fixed frame rate and is independent of the frame rate of the game. It is used for physics-related calculations and actions, such as moving Rigidbody components. FixedUpdate is preferred for physics because it ensures consistent physics calculations and prevents issues like forces being applied unevenly if calculated in Update, which might lead to unpredictable results due to frame rate variation .

The [SerializeField] attribute allows private fields to be visible and serialized in the Unity Inspector without changing their access level or promoting them to public. This attribute is significant for maintaining encapsulation while still exposing fields to be edited in the Unity Editor, providing a way to tweak values during design-time without compromising code structure .

Case sensitivity in Unity scripting, especially in MonoBehaviour callback methods like Update or OnCollisionEnter, is critical, as misnamed methods due to incorrect casing might not be recognized by Unity's execution engine, leading to bugs that can be difficult to trace. This issue significantly impacts debugging, as the script appears correct but fails at runtime. Maintaining strict adherence to naming conventions and casing helps prevent these errors, aiding in project maintainability by ensuring all scripts behave as expected .

You might also like