- Home /
How to change an object's parent without changing it's z position in Unity 2D.
All other methods for locking the z axis won't work. When the z-axis changes so wildly, the object tends to be moved behind the parent and other objects. This is the code on the player character that "grabs" the treasure. It works, but the treasure is hidden behind the second player because the z position changes.
void OnCollisionEnter2D(Collision2D other){
if (other.gameObject.tag == "Beholder") {
Debug.Log ("Take Treasure");
treasure.transform.position = new Vector2(gameObject.transform.position.x,gameObject.transform.position.y);
treasure.transform.parent = gameObject.transform;
}
if (other.gameObject.tag == "Treasure") {
treasure.transform.position = new Vector2(gameObject.transform.position.x,gameObject.transform.position.y);
treasure.transform.parent = gameObject.transform;
The treasure is purple, and player 1 is blue. Also sometimes the treasure sprite is squashed in relation to the player sprite. Only sometimes though.
try preserving the z position before reparenting.
float originalZ = treasure.transform.position.z;
treasure.transform.SetParent(gameObject.transform, false);
treasure.transform.position = new Vector2(
gameObject.transform.position.x,
gameObject.transform.position.y,
originalZ);
Didn't work. I can't tell you why. It happens at complete random, so if I change a few things around it shouldn't matter too much.
Storing the world position and reassigning it right after makes no sense, it will stay the same when setting a new parent.
Why use SetParent and tell it not to keep the world position, and then tell it to keep the world position as before in a new line?
That seem like a complete redundant action to me.
Format your code properly please. Use the 101010 button on it. Edit your question to do that. It's annoying and mostly impossible to read code that is pasted without any formatting. ;)
"How to change an object's parent without changing it's z position" Just change the parent. Use Transform.parent = whateverthenewparentis.
There is not going to be any change of position in the target object if you only change it's parent. The only thing that changes is the localposition because it get's a new parent that this vector refers to.
PS: $$anonymous$$ake sure your read the FAQ and watch this video, if you haven't already.
I can't do that. Its not the treasure that the player is colliding with. The treasure is somewhere off screen and teleports on top of the player whenever they touch the statue in the center. I have to change the x and y position.
I don't know whether you have a parent currently. If yes, unparent the current one first
treasure.transform.parent = null;
Then assign a parent to treasure.
Also give sorting order for layers (if u r using 2d sprite), so that the one which should come infront can be given priority.