- Home /
Update Parent/ Children From Script?
Is it possible for me to make an object a child of another object when a certain button is pressed, and vice versa?
I know how to use input, just need to know how to add/ subtract children from script.
Answer by always_beta · Jun 29, 2012 at 02:15 AM
Do you mean: childObject.transform.parent = parentObject.tranform
I guess? Let's say I have a objOne and objTwo. How do I use that to make objTwo a child of objOne?
Okay, after reading the script reference, I think I understand. So now I have this:
function OnCollisionEnter(theCollision : Collision){ if(theCollision.gameObject.name == "item"){ if(Input.GetButtonDown("Pick Up")){ item.parent = transform;
But it doesn't recognize the "item" in item.parent in the last line. It says "$$anonymous$$ identifier: 'item'"
So assume both objOne and objTwo are instances of GameObject, then: objTwo.transform.parent = objOne.transform.
You should use theCollision.gameObject.transform.parent = transform ins$$anonymous$$d of item.parent.
I don't under stand what you mean when you say "are instances of GameObject"..
Answer by aldonaletto · Jun 29, 2012 at 04:30 AM
@always_beta means that objOne and objTwo are GameObject references. Contrary to Flash and web javascript, in Unity the object name cannot be used as a reference to the object - Unity uses reference variables, which are the equivalents of C pointers - a reference holds the object address in memory (kind of... things are somewhat different in .Net/Mono).
In the case above, theCollision gives you several references to the object hit (gameObject, transform), which you can use to set parenthood:
function OnCollisionEnter(theCollision : Collision){ if (theCollision.gameObject.name == "item"){ if (Input.GetButtonDown("Pick Up")){ // Collision has a reference to the object's Transform as well // You must use it, since parent is a Transform property: theCollision.transform.parent = transform; } } }
Your answer
Follow this Question
Related Questions
Create multiple instances of an object 2 Answers
Make a simple tree 1 Answer
GetComponentInChildren(Renderer).active wont work? 2 Answers