Modifying Rect Transform values by Script

Hi.

I´m having some problems with the new UI because i´m creating an element that is previous saved as prefab.

My code is the next:

  GameObject newRoom = (GameObject)GameObject.Instantiate(room, room.transform.position, room.transform.rotation);
  
newRoom.transform.SetParent(roomsPanel.transform);

room is my prefab (GameObject) and the original have a Rect Transform component with the next values:

But the new element dynamically created have this other:

I tried this:

RectTransform rc = newRoom.GetComponent<RectTransform> ();
    rc = room.GetComponent<RectTransform> ();

But is not work, the values are the same.

I tried modifying the sizeDelta and the anchored position and works, but only with manual values for a specific screen size, if i use for example (-429.1f, -55.5f); for 800x480 screen and after when the same values open the game in a 1024x768 screen, the element was in other position :S

This only works if in the inspector I copy the component values and paste it in the new element, but this is not automatically and i need do it by script.

I need your help.

Thank You!

I went around with this a lot today and in final analysis I could not get the scaling working reliably when done under script control. Using the .SetParent() method is definitely necessary, or so it seems from what that method does, but I still could not get code-generated and/or code-manipulated UGUI stuff working right scale-wise.

My google-fu is exhausted. Can someone from Unity please post some short snippets of code that create fully-functional UI objects in a blank scene? And please can you do so without using the word ‘Prefab’ anywhere in your explanation.

It seems the problem is that the scale of the parent transform must be 1,1,1. And it is not.

Thanks, finally works, the problem was the Scale but not of the parent, i fix it modifying the scale to 1 before apply the sizeDelta and works perfect!:

newRoom.transform.SetParent(roomsPanel.transform);
newRoom.GetComponent<RectTransform> ().localScale = new Vector3 (1, 1, 1);
        newRoom.GetComponent<RectTransform>().sizeDelta = new Vector2(-35f, 0.5f);
        newRoom.GetComponent<RectTransform>().anchoredPosition = new Vector2(-16.6f, -160.0f*roomId);

Thank you very much!

1 Like