1
votes

I was trying to instantiate a prefab button inside a child of canvas. It's x and y axis are staying constant but Z axis is acting weird. It becomes -800 for some reason and I can't figure out why. Here is the code:

enter image description here

And when I press play, here is the result: enter image description here

as you can see, even though I set the rectTransform to something else, it still becomes -800 (I want it to be 0 or anything I want.). Any help would be appreciated. Thank you so much and take care.

1

1 Answers

1
votes

The position you see there in the RectTransform (and Transform) is the Local Position. When you instantiate an object, and parent it to another Transform, the Local Position will be updated to keep the object in the Instantiated position. It does that by modifying the Local Position. Another way to look at it, the World Position that you instantiated the object at, is still the same after you parented it.

The Instantiate method has an overload that accepts a bool InsantaiteInWorldSpace but it looks like you want to set some positions yourself. In that case, Transform also has a method SetParent that also has an overload accepting a bool worldPositionStays. You can visit the Unity docs page for SetParent here.

In the later case, you'd not set the parent during instantiation, but afterwards, and set bool to keep the object in the position you had manually set it to. IT all depends on how you want to position your item in relation to your hierarchy.