Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Non-hacky way to instantiate ui text objects?

Discussion in 'UGUI & TextMesh Pro' started by twoski, Sep 22, 2014.

  1. twoski

    twoski

    Joined:
    Mar 27, 2014
    Posts:
    27
    I am trying to create a panel which i can call something like AddText on and it will add a new Text object and parent it to the panel. There can be many lines of text so multiple text objects will be required.

    I have tried instantiating a Text UI element i had saved as a prefab, however i get errors when i create it. I assume this is because you can't instantiate UI elements without a parent canvas? Here is the error

    Type ISelectHandler expected EventTrigger received. i:1. Object reference not set to an instance of an object UnityEngine.EventSystems.EventSystem:Update()

    My alternate approach to this is to make a canvas with a text object parented to it and save it as a prefab. But this means every time i add a new line of text to the panel i will be instantiating a new canvas. This does not sound like the appropriate way to do this.

    Furthermore, how do i change the text in a Text object? Tehnically it is just a script parented to a RectTransform, so do i do something like GetComponent<Text>?
     
  2. PiMuRho

    PiMuRho

    Joined:
    Jul 11, 2012
    Posts:
    17
    I do it this way:
    Code (csharp):
    1.  
    2. Text tempTextBox = Instantiate(textPrefab, nextPosition, transform.rotation) as Text;
    3.                  //Parent to the panel
    4.                   tempTextBox.transform.SetParent(renderCanvas.transform, false);
    5.                   //Set the text box's text element font size and style:
    6.                    tempTextBox.fontSize = defaultFontSize;
    7.                    //Set the text box's text element to the current textToDisplay:
    8.                    tempTextBox.text = textToDisplay;
    9.  
     
  3. VoiiDzz

    VoiiDzz

    Joined:
    Oct 18, 2017
    Posts:
    1
    ma DUDE you saved my day
     
  4. nagarjunachada

    nagarjunachada

    Joined:
    Jul 10, 2018
    Posts:
    1
    U are a god
     
  5. JDeyby

    JDeyby

    Joined:
    Sep 14, 2017
    Posts:
    5
    Muchas Gracias me sirvio