CSharp Unity Cheatsheet
CSharp Unity Cheatsheet
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 .