1
votes

I am putting a prefab (basically an Image) onto a Canvas at "0,0,0" in a script (for debug sake). When I press play in the editor, this is carried out but the GameObject end up at "-3.051758e-05,-280,0" i.e. way off from 0,0,0. What could cause this?

The Canvas is a child of the root canvas and is set to max out its size in order to be as big as its parent.

Using Unity 4.6.

Update: Not 100% sure yet but when setting position using somegameobject.localPosition = somevector the positioning seems to work.

1

1 Answers

1
votes

transform.localPosition sets the position relative to the parents position whereas transform.position sets the position in worldspace. If you take a look at the canvas in scene view you will see that the bottom left corner of the canvas will be at 0, 0, 0 in worldspace, but 0, 0, 0 of the canvas is in its center. Since you have to instantiate a gameobject first and make it a child afterwards, it's position in worldspace is 0, 0, 0, but it's position in the inspector is its position relative to its parents position and will therefor not be 0, 0, 0 since the canvas doesn't sit a 0, 0, 0.

Setting the child with localPosition after instantiating will position it the way you want it relative to the canvas. 0, 0, 0 will then be in the center of the game view. The position of the child in worldspace would then be canvas.x, canvas.y, 0 (you won't see that in the inspector of course).