Instantiated UI prefab appearing in an unexpected location

I am trying to Instantiate a prefab panel as a child of another panel, but it is not appearing where I am expecting it. I feel like I must be missing a step somewhere.

GameObject panelAtk = GameObject.Find("Show Stats Panel Atk");
GameObject inputHowManyPrefab = Resources.Load("Prefabs/How Many Panel", typeof(GameObject)) as GameObject;
GameObject inputHowMany = Instantiate(inputHowManyPrefab, inputHowManyPrefab.transform.position, inputHowManyPrefab.transform.rotation, panelAtk.transform) as GameObject;

I was expecting something like this:

82048-howmany-001.png

The cloned prefab shows up in the hierarchy correctly, but at the wrong coordinates:

82050-howmany-002.png

The prefab’s rect transform looks like this:

Left        Top        Pos Z
9.8          210       0
Right      Bottom
10.2        11

… but the Instantiated panel’s transform is not even close.

Left              Top                 Pos Z
-365.2324    547.1365       0
Right            Bottom
385.2324     -318.1365

Any idea as to what I am missing?

Thanks.

Just instantiating is not enough for any RectTransform. they only work properly when childed to a canvas at any level in the hierarchy. for that use SetParent(parent, false). the false parameter is important because otherwise the GO keeps it’s world space values instead of readjusting for the UI. the parent is any gameobject below the canvas.

Thanks!

I was assuming that the 4th parameter of Instantiate was taking care of setting the parent. Once I called SetParent() and dropped that 4th parameter, it worked great.

The working code:

        GameObject panelAtk = GameObject.Find("Show Stats Panel Atk");
        GameObject inputHowManyPrefab = Resources.Load("Prefabs/How Many Panel", typeof(GameObject)) as GameObject;
        GameObject inputHowMany = Instantiate(inputHowManyPrefab, inputHowManyPrefab.transform.position, inputHowManyPrefab.transform.rotation) as GameObject;

        inputHowMany.transform.SetParent(panelAtk.transform, false);