Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Resolved How do I unparent an object without changing it's position?

Discussion in 'Scripting' started by jlorenzi, Feb 1, 2022.

  1. jlorenzi

    jlorenzi

    Joined:
    May 2, 2021
    Posts:
    293
    Fix: The reason I wanted to unparent the bat was to stop it from moving with the player, but for some reason that I still don't understand the bats position got locked when I unparented it so I couldn't move it, so I settled and made it so the player can't move when I don't want the bat to move. Yeah, it's lazy but hey, it works.

    Not much to say here, the title pretty much sums up the whole question.
    Here's what I've tried
    Code (CSharp):
    1. Vector3 originalBatPos = bat.transform.position + transform.position;
    2.  
    3. bat.transform.parent = null;
    4.  
    5. bat.transform.position = originalBatPos;
     
    Last edited: Feb 1, 2022
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,933
    It depends. Are you trying to preserve the object's position in the world? Or are you trying to preserve the object's position relative to its parent?

    Code (CSharp):
    1. // This will preserve the bat's local position
    2. bat.transform.SetParent(null, false):
    3.  
    4. // This will preserve the bat's world position
    5. bat.transform.SetParent(null, true);
    6. // which is also equivalent to
    7. bat.transform.parent = null;
     
    Madgvox likes this.
  3. jlorenzi

    jlorenzi

    Joined:
    May 2, 2021
    Posts:
    293
    I'm trying to preserve the bats world position, but the solution you gave me didn't work. I'm gonna run some debug statements to see what's going on