Hello, this is my first question here, so please be patient with me. I have a hierarchy of the following type:
I need to be able to change a child’s grandparent and parent, so that I keep the same hierarchical position. My game involves applying properties (visibility etc.) to all children and grandchildren of a certain grandparent. I need to change the object’s grandparent, so that it automatically receives its properties (which is decided upon collision). Also, all grandparents have an identical hierarchy. In other words, I need to change the hierarchy from the one above to the following:
I know how to get the parent of a parent (Child1.transform.parent.parent.transform
) , or set a new parent to an object (Child1.transform.parent = GrandparentB.transform;
). However, the latter will only move Child1 to GrandparentB (GrandparentB will become its parent) and not further down the hierarchy.
I suppose the solution is very simple, but so far I haven’t found any help in the forums.
In your two images you do not change the grandparent but just the parent of your child. The grandparents (the parent of the parent) does not change. Just as in real life. If you “change your parents” (i.e. being adopted by another family) you change your parents. Your new parents of course have different grandparents than your old parents. Sounds a bit strange but that’s how it would work. Instead of parents you can think of any other hierarchical structure. Imagine you live an a house in france. When you move to a new house that is located in spain you don’t have to change the “parent” of any of the two houses. You just move to the new house and at this point you now live in spain instead of france.
So in your case if you have a child inside the “parent” of GrandparentA, you just have to set the parent of your child object to the new parent that is located under GrandparentB.
Where and how you get the references to those gameobjects is up to you. You haven’t provided any code yet.
Of course technically it would be possible to change the parent of the parent. However than the result would not look like what you have shown. Because when you change the parent of the parent, the parent object would now be a child of the new grandparent. So it would look like this:
- Grandparent A
- GrandParent B
- Parent
- Child1
- Parent
- Child2
So when changing the parent of the parent Grandparent A would be empty since we moved the parent over to the new grandparent. I don’t think that’s what you want.
Well you can change the parent of any transform through transform.SetParent(Parent.transform);
You can use GameObject.Find()
, to find the parent, and then set the child as the parent of that object. For example:
GameObject Parent = GameObject.Find("Parent1");
Child1.transform.SetParent(Parent.transform);