Cant set my prefab position with Instanciate(Prefab)

I’m trying to create a list of Prefab for my uGUI but when i try to position the prefab it doesnt move to the position at all… if i check in the scene it’s at an other place completly… -561, 167, 0 … how do i move my prefab??

he’s a child of the current monobehaviour script.

for (var i = 0; i < SaveGames.Count; i++)
{
                var savedGame = Instantiate(SavedGamePanelPrefab);
                savedGame.SetInfos(SaveGames[i]);
                savedGame.transform.parent = _loadMenuPanel.transform;
                var rectTransform = (RectTransform) savedGame.transform;
                rectTransform.localScale = Vector3.one;
                rectTransform.sizeDelta = Vector2.zero;
                rectTransform.anchoredPosition = Vector2.zero;
                rectTransform.position = new Vector3(14, 131 * 75, 0);
                savedGame.gameObject.SetActive(true);
}

var rectTransform = savedGame.GetComponent();

The recttransform is not inherently built into “transform”, you’ll have to manually access it as a component.

Nonsense. RectTransform inherits from Transform. So you can access the RectTransform with .transform

To the OP: Setting positions manually for UI elements gets a bit weird. Try setting the position first, before parenting. Then parent with Transform.SetParent and set the second argument to false.

Apologies O.o, I have some vague memory of not being able to do that when I first tried the 4.6 gui. Guess I’ll be rewriting some of my code.

Also, you might try localPosition with local vectors after parenting as well. Both should work.

1 Like

still doesnt work with

for (var i = 0; i < SaveGames.Count; i++)
{
    var savedGame = Instantiate(SavedGamePanelPrefab);
    savedGame.SetInfos(SaveGames[i]);

    var rectTransform = (RectTransform)savedGame.transform;
    rectTransform.localScale = Vector3.one;
    rectTransform.sizeDelta = Vector2.zero;
    rectTransform.anchoredPosition = Vector2.zero;
    rectTransform.position = new Vector3(14, 131 + (75 * i), 0);
    savedGame.transform.SetParent(_loadMenuPanel.transform);
    savedGame.gameObject.SetActive(true);
}

the position i get is : -563, 9527, 0

prefab default : 0, 0, 0
parent : 227.5, 110.5, 0

EDIT

if i add

rectTransform.localPosition = Vector3.one;

the position i get is : -562, -167

See if using .SetParent(_loadMenuPanel.transform, false) helps. The second parameter will make it keep its local position (which you set in the line above it) - the default is to keep the world position instead.

1 Like

Also, in this case, you may sidestep the issue entirely by using a Vertical Layout group on the parent, instead of setting each position by hand. This is what it was made for.

2 Likes

i forgot about the false parameter it was written up…

thx a lot to tell it back! it work as expected now.

I will for sure take a look at Vertical Layout for my parent. its surely the UI thing i was looking for!

1 Like