Rect Transform with C#

Hello word
I want to instantiate an UI Element on position (Left: 0 Right:0 PosY:0 Height:75). I did created a prefab of that gameobject and used the script below.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class InstantiateData : MonoBehaviour
{
    public GameObject ChatTemplate;
    public GameObject ChatList;

    GameObject xChatTemplate;

    public void InstatiateChat ()
    {
        xChatTemplate = Instantiate(ChatTemplate,transform.position,Quaternion.identity) as GameObject;
        xChatTemplate.transform.parent = ChatList.gameObject.transform;
    }
}

I call this InstatiateChat function with a button. When i press my button it do successfully instantiate the button unfortunately the position & scale is wrong. Any idea about how to change position & size (Left: 0 Right:0 PosY:0 Height:75) of a UI element with script
Thanks in advance & sorry for my bad english

How did you set the anchoring? The position is always relative to the anchor point.

Have a look at the pages in the manual bundled with beta 18 called “Basic Layout” and “Creating UI Elements from Script”.

Anchor is top stretch

It looks like you are using the GameObject’s Transform instead of using it’s RectTransform. I always get the RectTransform and mess with that just to be sure. I don’t know if that’s your issue or not.

In Instantiate function there is no option for Rect Transform

You need to typecast the Transform to access it as a RectTransform. In other words, its RectTransform is its Transform, but you need to tell C# that it is being used as a RectTransform so that it knows that it has the extra functions.

RectTransform xChatRT = (RectTransform)xChatTemplate.transform;
xChatRT.anchoredPosition = something;
2 Likes

Thanks all for your help. It’s done now