Search code examples
c#unity-game-engineposition

Change UI RectTransform position


I have these lines :

GameObject bp = Instantiate(MyPrefab);
bp.transform.SetParent(GameObject.FindGameObjectWithTag("ContentFactory").transform);
bp.transform.localPosition = new Vector3(0, 0, 0);

Si, I just instantiate a prefab, I set a parent and I want to change the position.

My problem is, the function SetParent set a fixed position to my bp GameObject, and after that I don't know how to change this position. The last line change nothing.... The same with .position.

How can I change the position of bp ? Thanks !

Edit :

Inspector of ContentFactory :

enter image description here

Inspector of a bp :

enter image description here

Hierarchy (Content in blue is ContentFactory) :

enter image description here


Solution

  • Using transform.localPosition will use it relative position. If you want to change the position in world space, you need to use transform.position.

    GameObject bp = Instantiate(MyPrefab);
    bp.transform.SetParent(GameObject.FindGameObjectWithTag("ContentFactory").transform);
    bp.transform.position = new Vector3(0, 0, 0);
    

    EDIT:

    This is a UI Object with a RectTransform. You shouldn't move it with transform.position.

    It should be moved with:

    bp.GetComponent<RectTransform>().anchoredPosition = ...

    or

    bp.GetComponent<RectTransform>().anchoredPosition3D = ...

    Note that there are other things that play role when using RectTransform.

    This includes anchorMax and anchorMin which can be modified with:

    bp.GetComponent<RectTransform>().anchorMax = ...
    bp.GetComponent<RectTransform>().anchorMin = ...