How do I unparent an object by scripting
How do I unparent the object once i stop holding down the mouse button?
if (Input.GetKeyDown(KeyCode.Mouse1))
{
GameObject.transform.parent = gameObject.transform;
}
else if (Input.GetKeyUp(KeyCode.Mouse1))
{
GameObject.transform.parent = gameObject.transform;
}
Answer by thepotatisbulle · Apr 03, 2016 at 12:32 PM
I fixed the problem by using null
if (Input.GetKeyDown(KeyCode.Mouse1))
{
GameObject.transform.parent = gameObject.transform;
}
else if (Input.GetKeyUp(KeyCode.Mouse1))
{
GameObject.transform.parent = null;
}
Hey, Could you please give example of how you made this work? I have a game object that is parented by another. I would like to onClick unparent the child so that it does not follow the parent any longer.
Thanks for any help!
Answer by St4Rn3Rd012 · Dec 19, 2020 at 04:08 PM
@thepotatisbulle I know I'm a little late to the party with this answer, but luckily Unity provides a function for that.
transform.DetachChildren();
This places the responsibility on the parent gameObject to let go of all its children.
How do you use transform.DetachChildren();? Is it just transform.DetachChildren(object, object);, or transform.DetachChildren(object);, or something else?
How about reading the documentation?
https://docs.unity3d.com/ScriptReference/Transform.DetachChildren.html
This (DetachChildren) is the only reliable way I've found to detach a large number of children from a parent. The loop is not only more complicated, it does not reliably work.