- Home /
Random Null Reference Exception
This part of the script works, I'm just getting a null reference exception being thrown out even though it works.
if (EggNumber == 30f) {
SpawnerScript otharScript = GameObject.Find("SpawnObject").GetComponent<SpawnerScript>();
otharScript.Die();
}
It causes no problems, I guess I want to get this solved in case if it somehow does later.
Part of the error message:
NullReferenceException
UnityEngine.GameObject.GetComponent[SpawnerScript] ()
Answer by Sirithang · Sep 13, 2011 at 01:17 PM
Looking at the error, it seems that GameObject.Find("SpawnObject")
return null, because it cannot find the GameObject your looking for.
You should try :
if (EggNumber == 30f)
{
GameObject lFoundObj = GameObject.Find("SpawnObject");
if(lFoundObj != null)
{
SpawnerScript otharScript = lFoundObj.GetComponent<SpawnerScript>();
if(otharScript != null) // better to check if the script was retrieved too
{
otharScript.Die();
}
}
}
Answer by msknapp · Sep 13, 2011 at 01:18 PM
Either your game object returns null, meaning it does not exist in the scene, or the game object does not have the script attached to it. Try this:
if (EggNumber == 30f) {
GameObject g = (GameObject)GameObject.Find("SpawnObject");
if (g != null) {
SpawnerScript otharScript = g.GetComponent<SpawnerScript>();
if (otharScript != null) {
otharScript.Die();
} else {
Debug.LogWarning("otharScript was null.");
}
} else {
Debug.LogWarning("Game object was null.");
}
}
Your answer
