Itération 122442
Itération 122442

Reputation: 2962

Unity3d understanding positioning system

I'm trying to instantiate an object (A) as a child of a canvas. The position of A is set using a B object's position, also a child of the Canvas.

Not sure if this is useful for my question, but A and B both have a child.

When I spawn A, it's position is not B's position at all, even if my debug.log() says so.

Here is what I have:

http://prntscr.com/czz084

Here is what the debug says:

http://prntscr.com/czz0dt

Here is the code:

 if (Input.GetButtonDown("Fire1"))
        {
            GameObject Laser_Projectile = Instantiate(Resources.Load("Sprites/Object_Laser_Projectile") as GameObject);
            Laser_Projectile.transform.SetParent(GameObject.Find("Canvas").transform, false);
            this.transform.localPosition = GameObject.Find("Player_Objects").transform.localPosition;

I tried to work with position and localPosition, no way to make it work. I also tried to use the setParent argument (false or true), but setting it to true makes it even worst.

My question is: What I am missing, what am I not understanding? I never had this problem before.

Upvotes: 1

Views: 2503

Answers (1)

Alfie Goodacre
Alfie Goodacre

Reputation: 2793

You are setting the localPosition of the transform, this sets it relative to its parent, but you are setting it to an unrelated object's localPosition instead of its global position (transform.position), which will end up being incorrect. In this case, you can compare the parent's world position to the other object's world position like so

Vector3 thePos = this.transform.parent.position - GameObject.Find("Player_Objects").transform.position;

Then you can set the localPosition of the object using this new Vector3

this.transform.localPosition = thePos;

Upvotes: 4

Related Questions