Search Unity

Rect Transform with C#

Discussion in 'Unity UI (uGUI) & TextMesh Pro' started by Ankit-Priyarup, Sep 4, 2014.

  1. Ankit-Priyarup

    Ankit-Priyarup

    Joined:
    Mar 7, 2013
    Posts:
    52
    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.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. public class InstantiateData : MonoBehaviour
    6. {
    7.     public GameObject ChatTemplate;
    8.     public GameObject ChatList;
    9.  
    10.     GameObject xChatTemplate;
    11.  
    12.     public void InstatiateChat ()
    13.     {
    14.         xChatTemplate = Instantiate(ChatTemplate,transform.position,Quaternion.identity) as GameObject;
    15.         xChatTemplate.transform.parent = ChatList.gameObject.transform;
    16.     }
    17. }
    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
     
  2. appels

    appels

    Joined:
    Jun 25, 2010
    Posts:
    2,685
    How did you set the anchoring? The position is always relative to the anchor point.
     
  3. runevision

    runevision

    Unity Technologies

    Joined:
    Nov 28, 2007
    Posts:
    1,686
    Have a look at the pages in the manual bundled with beta 18 called "Basic Layout" and "Creating UI Elements from Script".
     
  4. Ankit-Priyarup

    Ankit-Priyarup

    Joined:
    Mar 7, 2013
    Posts:
    52
    Anchor is top stretch
     
  5. webbut

    webbut

    Joined:
    Jun 25, 2014
    Posts:
    20
    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.
     
  6. Ankit-Priyarup

    Ankit-Priyarup

    Joined:
    Mar 7, 2013
    Posts:
    52
    In Instantiate function there is no option for Rect Transform
     
  7. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    7,075
    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.
    Code (csharp):
    1.  
    2. RectTransform xChatRT = (RectTransform)xChatTemplate.transform;
    3. xChatRT.anchoredPosition = something;
    4.  
     
    JackofTraes and T_Lavell like this.
  8. Ankit-Priyarup

    Ankit-Priyarup

    Joined:
    Mar 7, 2013
    Posts:
    52
    Thanks all for your help. It's done now
     
unityunity