Three small things that took me longer to find than they should have. Nothing complicated, just easy to never bump into unless someone points them out.
- RequireComponent auto-adds missing dependencies
c#
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
}
If a script can't function without a Rigidbody, this stops you from forgetting to attach one and hitting a null reference two scenes later, once you've forgotten you ever needed it in the first place.
- OnValidate catches bad config before you hit Play
c#
public class EnemyStats : MonoBehaviour
{
public int health = 100;
void OnValidate()
{
if (health < 0)
health = 0;
}
}
Runs in the Editor the moment a value changes in the Inspector, even without pressing Play. Clamp a bad value the second it gets typed in, instead of finding out at runtime.
- Time.unscaledDeltaTime keeps UI moving when gameplay pauses
c#
void Update()
{
if (isPaused)
{
fadeAlpha += Time.unscaledDeltaTime * fadeSpeed;
}
}
If you pause with Time.timeScale = 0, anything using regular delta time freezes too, including your UI. Use unscaledDeltaTime for interface stuff. Gameplay stops, menu keeps moving.
What's a small Unity hack you use constantly that most people don't know about?
Tags: #unity #gamedev #csharp #beginners
Top comments (0)