- Home /
Dynamically create GUIText from script.
how can I create GUIText from script.. Below is the script that I am trying to do. But there has an error "Null Reference" in accessing to btnTexts...
private GUIText[] btnTexts; public Font font;
public void CreateTexts() {
btnTexts = new GUIText[numButtons];
for (int i = 0; i < numButtons; i++) {
//Create a Text btnTexts[i] = new GUIText(); btnTexts[i].font = font;
btnTexts[i].transform.position = new Vector3(0.0f, startPosY, 2.0f);
btnTexts[i].text = "Test";
}
}
The above code is not working and always saying NullReference Exception... :(
Answer by Mike 3 · Aug 26, 2010 at 11:34 AM
You'll need to use AddComponent instead of new GUIText to create the GUIText - GUIText components don't work without a gameobject
Something like this should do it:
//Create a Text
GameObject go = new GameObject("GUIText " + i);
btnTexts[i] = (GUIText)go.AddComponent(typeof(GUIText));
btnTexts[i].font = font;
//etc
I changed my code to ur suggestion and it still doesn't work... " The error is cannot explicily convert type UnityEngine.Component to UnityEngine.GUIText..."
GameObject go = new GameObject("GUIText " + i); btnTexts[i] = go.AddComponent(typeof(GUIText));
btnTexts[i].font = font;
btnTexts[i].material.color = new Color(1.0f, 1.0f, 1.0f);
btnTexts[i].transform.position = new Vector3(0.0f, startPosY, 2.0f);
btnTexts[i].text = "Test";
Answer by Thet Naing Swe · Aug 26, 2010 at 12:02 PM
Sry,,, I Confused between JavaScript and C# Style.. It works like that
GameObject go = new GameObject("GUIText " + i); btnTexts[i] = go.AddComponent();
btnTexts[i].font = font; btnTexts[i].material.color = new Color(1.0f, 1.0f, 1.0f);
btnTexts[i].transform.position = new Vector3(0.0f, startPosY, 10.0f);
btnTexts[i].text = "Test";