Was wondering if there was a way to require a variable be assigned via inspector, ala RequireComponent. I’m sure this has been asked plenty of times before, but all searches of Google and UA returned results about NullReferenceExceptions people were seeing because they forgot to assign something via inspector (which is exactly what I’m trying to prevent). I’m writing code that’ll be used by others, including non-technical folks, so leaving a comment like
You could do Hexers answer but if its not assign make it so the launcher stops playing.
public GameObject ABC;
if(ABC != null){
//Line of code
}
else
{
Debug.LogError("assign the gameobject ABC in the inspector before resuming");
UnityEditor.EditorApplication.isPlaying = false;
}
It is better to do these checks once in Start or Awake and proceed as normal than indent the code every time before use (bailer).
The problem with this solution is the code will continue to run for the rest of Starts or Awakes, even though we set the isPlaying to false, and this will most probably cause other NullReferenceExceptions down the line, which could confuse the user.
using UnityEngine;
internal static class MyDebug
{
public static void Assert<T>(T variable) where T : class
{
Debug.AssertFormat(variable != null, "The instance of '{0}' is `null`.", typeof(T).Name);
}
}
The usage:
public class Entity : MonoBehaviour
{
public ExplosionDamage Damage;
private void Awake()
{
MyDebug.Assert(Damage); // will print "The instance of 'ExplosionDamage ' is `null`."
}
}