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;
        }

2 Answers

2

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!

@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?

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.