- Home /
nullReferenceException when comparing tag in a search for a specific parent. help.
below is my function i wrote to find a parent with a specific tag. its resulting in a nullReferenceException.
here are the specifics of the the gameobjects and their tags. I will start with the child. childA's tag is "tagA"; parentA's tag is "Untagged"; this is the defualt value if you do not add a tag. parentB's tag is "tagB";
the parental structure is as follows. parentB>ParentA>childA
so childA's parent is ParentA and ParentA's parent is ParentB
This is how im using the function below. its running in a script attached to childA. GameObject parentB = findElderWithTag(gameObject, "tagB");
It should return the gameObject of ParentB.
private GameObject findElderWithTag(GameObject aGameObject, string aTag){
if(aGameObject.transform.parent.tag!="Untagged"){
if(aGameObject.transform.parent.tag==aTag){
print(aGameObject.transform.parent.gameObject.name);
return aGameObject.transform.parent.gameObject;
}
else{
return findElderWithTag(aGameObject.transform.parent.gameObject, aTag);
}
}
else{
print("this should print only once");
return findElderWithTag(aGameObject.transform.parent.gameObject, aTag);
}
}
The error happens on the second line and on the return at the bottom. the print line at the bottom fires once, as it should.
here is the specific error message:
NullReferenceException: Object reference not set to an instance of an object DoorAutoCloser.findElderWithTag (UnityEngine.GameObject aGameObject, System.String aTag) (at Assets/Standard Assets/UserScripts/DoorAutoCloser.cs:42) DoorAutoCloser.findElderWithTag (UnityEngine.GameObject aGameObject, System.String aTag) (at Assets/Standard Assets/UserScripts/DoorAutoCloser.cs:53)
this was happening as i was executing this in the Awake() function. i moved the execution to the Start() function and there was no error.
could someone explain why this was happening. are parents not assigned until after awake()?
Answer by hexagonius · Feb 16, 2017 at 09:46 PM
No, really. Maybe you had the script on more than one gameobject and that did not have a parent. A little advice though, since your method is very specific and could be generealised a bit more:
using UnityEngine;
public static class TransformHelper{
public static GameObject FindElderWithTag(this GameObject gameObject, string tag){
Transform current = gameObject.transform;
while (current.parent != null) {
if (current.parent.CompareTag (tag))
return current.parent.gameObject;
current = current.transform.parent;
}
return null;
}
}
Now you can do that:
GameObject parentB = gameObject.findElderWithTag("tagB");