- Home /
UnassignedReferenceException and Null-Check
I often check in Start()-method, if all needed references are set in inspector. So i wrote a utility method, for this like this:
public static void WarnIfNull(object o, string name) {
if (o == null) {
Debug.LogWarning(name + " is NULL");
...
so i can use it in component init code like this:
public class MyComponent : MonoBehavior {
public AudioClip sound;
void Start() {
MyLogUtils.WarnIfNull(sound, "sound");
...
Nothing special, interesting so far... But it does not work. Assuming i forgot to assign reference in inspector. If i null-check inside of MyComponent.Start(), null check works correct. But if doing exact same null-check inside of MyLogUtils.WarnIfNull(), null check is FALSE. I can not explain this, it is really weird.
So i tryied to debug it, if object is not null, then what is it? (it was never assigned). I can cast it to AudioClip like this
if (o is AudioClip) {
AudioClip a = (AudioClip) o; // this works
}
but if i call any method/property from this object like this:
var a_name = a.name;
a_name.ToString();
i am getting UnassignedReferenceException.
I know, it sounds strange, that null-check of same object in call-stack behaves not same. But is looks like this. I do not really understand what is the reason for that. Docs for UnassignedReferenceException somehow do not explain it.
So my missing-reference method looks like this now:
public static void WarnIfNull(object o, string name) {
bool unassigned = false;
if (o is AudioClip) {
try {
AudioClip a = (AudioClip) o;
var a_name = a.name;
a_name.ToString();
} catch (UnassignedReferenceException e) {
unassigned = true;
}
}
if (o == null || unassigned) {
Warn(name + " is NULL (unassigned in inspector, but somehow can be not null)");
}
}
Any suggestions explanations are welcome. So, my question:
Why the same reference is null in one methode and not null in another. I just pass it by reference but, null-check result ist different. Is this some special UnityEditor stuff i should know?
Have you tried changing the signature of your utility function to:
public static void WarnIfNull(UnityEngine.Object o, string name)
Answer by Vencarii · Feb 27, 2018 at 01:45 PM
So you don't get any error when you use MyLogUtils.WarnIfNull(sound, "sound"); in Start()?
My guess would be that MyLogUtils isn't there in your Start() method, maybe?
Exactly. I just forgot to set sound to one component, and wonder that no warning was on console. I suspect that UnityEditor makes some art of fake-dummy-object for some reason. So I need some reliable way to detect missing referneces. Just null check seems not to be enought.So you don't get any error when