Hi there,
I need to find some GameObject children by their name. This work perfectly fine if the child I am searching exists.
But if it does not exist, I get this exception:
NullReferenceException: Object
reference not set to an instance of an
object
According to the Unity docs, I would expect transform.find to return null instead of throwing an exception.
Any ideas?
GameObject productContainer; // parent Object that contains several (or null) children
GameObject item;
item = productContainer.transform.Find("product1").gameObject;
if (item == null)
// this code is never reached - if "product1" does not exist an exception is thrown
Debug.Log("Not found");
else
Debug.Log("Found"); // this code works if "product1" exists
It may return a Transform reference or it may return null. However you put a .gameObject right behind it. So if Find returns null you basically do:
item = null.gameObject;
which of course will throw a null reference exception since you can’t access the gameObject property of a null value. If you want to test if an object was found you have to check the return value of the method before doing anything with it:
Note that it would be simpler to just define your item variable as Transform. However if you really need / want to use a GameObject variable you have to do it this way.