armnotstrong
armnotstrong

Reputation: 9065

unity2d transform and position of instantiated UI object

according to the document(quoted bellow for convenience)

public static Object Instantiate(Object original, Transform parent);

if I instantiate a prefab and pass a transform as the second parameter then the newly instantiated gameobject will be the child of the specific gameobject of the passed transform, right? And yet I presume that the position of the newly instantiated gameobject should be adjusted according to parent.

I made an UI-Image as a prefab: with the posX, posY configured and anchored as following:

enter image description here

And in the hierarchy:

enter image description here

And the instantiate C# script snippet:

GameObject pageIcon = transform.parent.FindChild("PageIcon").gameObject;
Instantiate(unSelectDot, pageIcon.transform);

And the result is that the newly instantiated object have a weird PosX and PosY: enter image description here Why does that happen? who changed the PosX and PosY? Did I misunderstand something?

Upvotes: 0

Views: 571

Answers (2)

Programmer
Programmer

Reputation: 125255

Why does that happen? who changed the PosX and PosY? Did I misunderstand something?

The solution to this problem depends on your Unity version.

Before Unity 5.5, when you do Instantiate(unSelectDot, pageIcon.transform);, the GameOject will be instantiated in world space instead of the position of the prefab.

From Unity 5.5 and above, when you do Instantiate(unSelectDot, pageIcon.transform);, the GameOject will use the Object position as the local position by default.

It is very likely that you are using Unity version under Unity 5.5. In this case, pass false to the third parameter of the Instantiate function.

Instantiate(unSelectDot, pageIcon.transform, false);

If this does not work, try true. Although, false should do it.

Note from Unity 5.5 release Note:

Core: Using Object.Instantiate(Object, Transform) will now use the Object position as the local position by default. This is a change from the 5.4 behaviour, which used the Object position as world.

Upvotes: 1

itay_421
itay_421

Reputation: 351

What I do when I want to Instantiate an object relative to its parent is like:

Instantiate(unSelectDot, GameObject.Find("PageIcon").transform);

Try this, I hope it will work for you

Upvotes: 0

Related Questions