- Home /
v4.6 Create GUI Elements Via Script?
Hello
I am a little bit affraid, because I think the solution must be so easy... BUT, like the title says, I want to create a Text just like
Text text = new Text();
maybe also
Text str = new Text("Hello");
But it keeps saying "`UnityEngine.UI.Text.Text()' is inaccessible due to its protection level"
So, is it just not possible?
Thanks in advance
Felix
Answer by AyAMrau · Sep 05, 2014 at 03:15 AM
UI elements are components just like most things you use in unity, so just call AddComponent():
Text text = gameObject.AddComponent<Text>();
text.text = "Hello";
$$anonymous$$eep in $$anonymous$$d that they will be created with default settings, so it may be better to spawn prefabs with those components already added and set up.
Thank you very much for your answer, but unfortunately this does not work like expected:
public void WriteTextOnScreen(string pText, int pX, int pY) {
Text str = gameObject.AddComponent<Text>();
str.text = pText;
str.transform.position = new Vector2(pX,pY);
}
This is the call:
ms.WriteTextOnScreen("10",(int)transform.position.x, (int)transform.position.y);
and I get this:
Can't add 'Text' to $$anonymous$$ain Camera because a 'Text' is already added to the game object! A GameObject can only contain one 'Graphic' component
Well is there already a Text component on the same object?
Probably need to just work out the positioning. After its spawned look at it in the inspector, make sure it's size is more than 0, and that it's placed within view in the scene.
Your answer
Follow this Question
Related Questions
4.6 GUI Button inside a scrolling Text Box 0 Answers
Text object can't be edited 3 Answers
[4.6] Add scroll wheel functionality to scroll rect 2 Answers
Unity v4.6 Joystick? 2 Answers
C# GUI Button 2 Answers