Best way to check that elements are setup in inspector propertly?

I’ve had a case where the Prefab I set into a SerializedField was deleted and I didn’t get an obvious error.

What’s the best way in Unity class to check that you have something assigned in a field expected to be set in the Insprector?

Best I can comeup with so far is to add an if statment in the Awake to check if it’s null and Log an error, but is there a better way? I know RequireComponent does a similar thing for components that should be attacked.

Thanks.

The proper place for field validation is in a special Unity Callback method called OnValidate()

Here’s a practical example of how this would work:

[SerializeField] Health health;
[SerializeField] Animator animator;
[SerializeField] float minSpeed = 2.0f;
[SerializeField] float maxSpeed = 4.0f;

//OnValidate is called whenever the component's values are updated or when GameObject this component is attached to is selected
void OnValidate()
{
    //Simple check and complain
    if(health==null) Debug.LogWarning($"{name} does not have a Health component assigned");
    //Simple check and attempt to correct
    if(animator==null) 
    {
         animator = GetComponent<Animator>();
         if(animator==null) Debug.LogWarning($"{name}has no animator assigned, and no animator is present on the GameObject");
     }
     //Ensuring min/max values
     if(maxSpeed < minSpeed) 
     {
          (maxSpeed, minSpeed) = (minSpeed, maxSpeed);
     }
}
1 Like

Privacy & Terms