DEV Community

Cover image for 3 Unity Hacks Most Tutorials Never Teach You
Muhammad Talha Malik (Malik)
Muhammad Talha Malik (Malik)

Posted on

3 Unity Hacks Most Tutorials Never Teach You

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.

  1. RequireComponent auto-adds missing dependencies

c#
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;

void Awake()
{
    rb = GetComponent<Rigidbody>();
}
Enter fullscreen mode Exit fullscreen mode

}

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.

  1. OnValidate catches bad config before you hit Play

c#
public class EnemyStats : MonoBehaviour
{
public int health = 100;

void OnValidate()
{
    if (health < 0)
        health = 0;
}
Enter fullscreen mode Exit fullscreen mode

}

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.

  1. 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)