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?