‘parent’ is a reference to the parent Transform, therefore it too has a parent property.
Of course, I personally would avoid a design that required static hierarchies in its structure. I usually have some script that I put on the ‘root’ GameObject that represents that collection of GameObjects (which I call an ‘Entity’). You can then dig up the hierarchy chain to get that script. This can easily be done with the GetComponentInParent method:
Yes, that method searches continuously up the parent chain until it reaches the root of the scene.
The script I usually use to represent entities is this one:
But it doesn’t have to be as complex as that one. It could just be a script called ‘Entity’ and have no real code in it.
Like so:
public class Entity : MonoBehaviour
{
}
//elsewhere for destroy
Destroy(this.gameObject.GetComponentInParent<Entity>().gameObject);
Another method is I have a ‘tag’ titled ‘Root’, and search up the parent chain for the GameObject with that tag.
Destroying your parents often leads to unintended consequences. I tend to use ExecuteEvents.ExecuteHierachy. The parent object can then choose to ignore or process the event as appropriate.
I mainly mention it as a caution. I once inherited a zombie survival project. Each wall in every house was a destructible object. Each house was part of a village.
The logical structure would have been to parent all the walls to a house, and parent all the houses to the village.
But the destructible object system used Destroy(transform.root.gameObject). Every destructible object in the scene was it’s own parent. Which made level design a nightmare. I quickly got sick of moving a house and leaving one wall behind, and went back and removed every line that referred to transform.root.
Needless to say transform.root has made it into my ‘not suitable for production’ list. I now use various versions of climbing the hierarchy to find something willing to deal with the event.
transform.parent.parent is the answer to the question you asked. I’m not sure how tags came into this question at all, but tags are unrelated to either the question asked or the answer given.
Yup. Once someone posts a correct answer we have a general habit of navel gazing. Transform.parent.parent will work for simple games and prototypes. In some cases the fastest solution to code is the best answer.
but i already have more than 15 identical prebas clons, with the same tag…
and i need to destroy 5 parents …
and i need to destroy all the gameobject hirarchy.
and this line is not working…