Search code examples
c#unity-game-engineunity-ui

If I assign an Object as GameObject, I cant get the RectTransform to work. How to fix that?


I want to give my Parent GameObject Inventory spicific rec-coordinates via this line of code: Inventory.GetComponent<RectTransform>().position = new Vector3(500f, 0f, 0f);

In the editor, the object Inventory is assigned as a GameObject, so it keeps changing the rec-coordinates to world-coordinates. I've tried assigning the Inventory as a Transform and RectTransform but it says that there is a missmatch in the type.

How can I fix that, either by fixing my code or by assigning it as something different?


Solution

  • You should modify the RectTransform's localPosition:

    Inventory.GetComponent<RectTransform>().localPosition = new Vector3(500f, 0f, 0f);
    

    Even without RectTransform (localPositions seems to be inherited/shared between Transform&RectTransform):

    Inventory.transform.localPosition = new Vector3(500f, 0);