Create UI Text from script
I have a Panel with the Vertical Layour Group component on it. If I create a UI Text from the editor everything seems to be ok, but now I need to create the same UI Text but from the code.
I Tried to look into the web, but nothing seems to work.
This is my Canvas's Structure:
Root ..HUD (Canvas) ....InfoPanel (Panel) <- Here I need to create a new text.
and I tried this code:
List<GameObject> textList = new List<GameObject>();
public void createMessage(string text, Color color)
{
if(color == null)
{
color = Color.green;
}
if(text == null)
{
text = "";
}
GameObject newText = new GameObject("text", typeof(RectTransform));
var newTextComp = newText.AddComponent<Text>();
//Text newText = transform.gameObject.AddComponent<Text>(); //This is the old code, it's generates a Null Exception
newTextComp.text = text;
newTextComp.font = fontMessage;
newTextComp.color = color;
newTextComp.fontSize = 16;
textList.Add(newText);
}
This code creates the UI Text (I think) but I can't see anyhig on the panel that is attached to this script.
Answer by Jason2014 · Feb 24, 2016 at 09:47 AM
Insert new text as children of specified panel using SetParent function. As argument take InfoPanel.transform.
http://docs.unity3d.com/ScriptReference/Transform.SetParent.html
Thanks you so much, that it's.
This is my new code for reference:
public void create$$anonymous$$essage(string text, Color color)
{
if(color == null)
{
color = Color.green;
}
if(text == null)
{
text = "";
}
GameObject newText = new GameObject(text.Replace(" ", "-"), typeof(RectTransform));
var newTextComp = newText.AddComponent<Text>();
//newText.AddComponent<CanvasRenderer>();
//Text newText = transform.gameObject.AddComponent<Text>();
newTextComp.text = text;
newTextComp.font = font$$anonymous$$essage;
newTextComp.color = color;
newTextComp.alignment = TextAnchor.$$anonymous$$iddleCenter;
newTextComp.fontSize = 10;
newText.transform.SetParent(transform);
}