Andromelus Andromelus - 1 year ago 262
C# Question

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

says so.

Here is what I have:

Here is what the debug says:

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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download