Question:
How to check if a public gameObject of a MonoBehaviour has been assigned in the inspector in
Unity3D, as the comparison for null (object==null)
fails.
Concrete Example:
I am about to write a generic method for Unity3D, that can be called on any nullable object. It checks if the object is null and if so it writes a Debug.LogError(customMessage)
. The Method looks like as follows:
public static bool IsNull<T>([CanBeNull] this T myObject, string message = "")
{
if (myObject!= null) return false;
Debug.LogError("The object is null! " + message);
return true;
}
The method can be called on any nullable object, anywhere in the code, for example within this simple Monobehaviour:
public class TestScript : MonoBehaviour
{
public GameObject testObject = null;
public void TestObject()
{
var result = testObject.IsNull("Error message");
Debug.Log(result);
Debug.Log(testObject);
}
}
For most use cases my method works perfectly and saves a lot of time during encoding/debugging. But my problem now is that if I haven't signed the "testObject" in the editor, my test won't work because the testObject seems to be not null, but it's also not usable because it's not assigned. In this case, the console output is:
False
null
How comes that (myObject == null)
is false, while the Debug.Log(testObject)
gives me null
as long as the corresponding object has not been asigned in the unity inspector.
Edit/Solution:
Thanks to the help from derHugo I ended up with this generic code snippet:
public static bool IsNull<T>(this T myObject, string message = "") where T : class
{
switch (myObject)
{
case UnityEngine.Object obj when !obj:
Debug.LogError("The object is null! " + message);
return true;
case null:
Debug.LogError("The object is null! " + message);
return true;
default:
return false;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…