- Home /
The question is answered, right answer was accepted
Does transform.root work when a parent is made the child of another object through script?
Does transform.root work when a parent is made the child of another object through script? It isnt working for me. In one script I create a weapon, "item" with a child and a child of that child, which has a script that is used to detect collisions:
Transform item =(Transform)Instantiate(itemPrefab, itemPosition.transform.position, itemPosition.transform.rotation);
item.parent = itemPosition.transform;
On the child of the child of "item", the script which is used to detect collisions has this code:
Transform playerTransform;
void Awake () {
playerTransform = transform.root;
}
But transform.root returns only "item," not the parent of the parent of the parent... of item, which I though would be the root, and which I am trying to access. Doing a search for the tag of the very first parent won't work because I will have multiple players that all have this sort of item.
Is there any way to access the very first parent? I've also tried "player transform = transform.parent.transfrom.parent.transform.parent etc...", but that returned a null reference exception when I started accessing parents of "item."
Answer by meat5000 · Feb 27, 2015 at 02:12 AM
root always refers to the top-most transform.
The problem is that you are making a 'snapshot' of a transform and probably assuming it will always refer to transform.root. It will simply take the instantaneous values of whatever the transform root is at that time.
I think you are right. It seems that the problem is that I used transform.root in the awake function, which was called before "item" was even parented to the other object.
Indeed, if you have moved your object hierarchy around, transforms assigned using an alias (parent, child, root) will need to be reassigned as they may very well refer to different transforms.
Using Start ins$$anonymous$$d of Awake usually has better results; as you notice, it takes time for the objects etc to load.
Follow this Question
Related Questions
Getting the topmost parent 1 Answer
Make a simple tree 1 Answer
Adressing a Child Object after it´s unparented 0 Answers
Making a list of obect's parents their parents from one script. 0 Answers