Thursday, October 5, 2017

gui - How to dynamically create an UI text Object in Unity 5?


I have been searching for something that should be simple, but Unity 5's documentation on that is fairly outdated. What I want to achieve is to be able to create UI Text totally from script, i.e. fully dynamically - in my real case application, I will do that in a loop of not pre defined number of iterations.


A search using Google will find quite many examples on how to do that, but all I saw either use methods that are already deprecated (are from before Unity version 5) or are simply wrong (no surprise here...). I already know that I should first add a Canvas to my project, then I should include using UnityEngine.UI in my C# code, and also that I could declare a UI Text like Text _guitext.


However, the code below does not work. I mean, it's not that it crashes, but rather that nothing is shown:


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


public class MyClass: MonoBehaviour {


Text _guitext;

// Use this for initialization
void Start () {
_guitext.text = "testing";
}

// Update is called once per frame
void Update () {

}
}

Worse than that, it seems that while game is played, no new object appears in the object hierarchy list.


Could you please point me out in the right direction here? Thanks.



Answer



I think what you are looking for is something like following:


GameObject CreateText(Transform canvas_transform, float x, float y, string text_to_print, int font_size, Color text_color)
{
GameObject UItextGO = new GameObject("Text2");

UItextGO.transform.SetParent(canvas_transform);

RectTransform trans = UItextGO.AddComponent();
trans.anchoredPosition = new Vector2(x, y);

Text text = UItextGO.AddComponent();
text.text = text_to_print;
text.fontSize = font_size;
text.color = text_color;


return UItextGO;
}

It means, you first create an Empty GameObject. Then you add a Text component, with the specific local and/or anchored parameters, set the desired text and its color, then you make this object a child of the empty game object.


You want to retrieve the UI Text information from or set variable of that object you've created via script, you can then just use yourGOname.GetComponent().text, yourGOname.GetComponent().font, etc.


And of course, for that to work you need to be using UnityEngine.UI.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...