Getting null pointer unless I give condition if it is null
I'm writing a transform extension that will return me the component of a child of a specified object:
TransformExtension.cs
public static T find <T> (this Transform m_transform, string m_name) where T: Component {
T found_component = null;
foreach (Transform child in m_transform) {
if (child.GetComponent<T> () != null) {
if (child.name == m_name) {
found_component = child.GetComponent<T>();
}
}
}
return found_component;
}
Here I'm looking up a child: FindTest.cs
void NullExceptionMethod()
{
Image image_child = transform.find<Image> ("image_child");
Debug.Log (image_child);
}
void WillWorkFineMethod()
{
Image image_child = transform.find<Image> ("image_child");
if (image_child != null) {
Debug.Log (image_child);
}
}
Method names are hopefully self-explanatory. If I set up a condition to check whether that object exists, it will return the object, if not, it will spit out a null exception.
Strange, huh? What's a better way to resolve this?
Answer by Glurth · Feb 06, 2016 at 03:51 PM
No need to look through the children manually, you can simply use this function instead: http://docs.unity3d.com/ScriptReference/GameObject.GetComponentsInChildren.html This function will give you an array of all components, of a particular type, that exist in the game object, and it's children. ( I just noticed, this is actually DIFFERENT from your function: yours will only check immediate children, as opposed to including "grand-children" and all other "decendants" as well- sorry if that invalidates this as an answer!)
You could then loop through the returned output array to check the compoents' name or image, or whatever.
Regarding the Exception error your are getting: if you pass a null value to a Debug.Log() statement, rather than a valid string (or object that can be converted to a string), this will always generate a runtime exception error.
Your answer
![](https://koobas.hobune.stream/wayback/20220612063148im_/https://answers.unity.com/themes/thub/images/avi.jpg)