transform.find exception if child does not exist
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
Thanks in advance!
Answer by Bunny83 · Feb 10, 2018 at 12:26 PM
Look at this line carefully:
item = productContainer.transform.Find("product1").gameObject;
When you call the method
productContainer.transform.Find("product1")
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:
GameObject item;
Transform tmp = productContainer.transform.Find("product1");
if (tmp == null)
Debug.Log("Not found");
else
{
item = tmp.gameObject;
Debug.Log("Found");
}
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.
Thanks for your perfect explanation! Can't believe I haven't seen it before...
Your answer
Follow this Question
Related Questions
Static function not working in between screen 2 Answers
How to change rotation for a FirstPersonController through script. 0 Answers
Needing a hand circumventing a "Missing Reference Exception". Any help sincerely appreciated! 1 Answer
Why does FindObjectOfType().transform return a null reference 1 Answer
Object reference not set to an instance of an object - Jumping Scripts (C#) 1 Answer