- Home /
Best practice for creating Canvas text in Javascript?
I'm new to using Canvas and currently trying to convert a game that heavily uses OnGUI to using Canvas. This game has a LOT of textboxes and buttons, and they come and go in many sizes and locations with text that is constantly changing. So I would like to create and edit them via a script rather than in the editor.
In OnGUI I could do this with one line of code:
var foo = "Changeable text";
var x = 0;
var y = 0;
var w = Screen.width;
var h = Screen.height/8;
function OnGUI () {
GUI.Box(Rect(x,y,w,h), foo); //Note that GUI.Box has a nice, semi-transparent background
}
However, if I want to have the same result with Canvas (including the semi-transparent background) I need a LOT more code:
var fooBox : GameObject;
var fooPrefab : GameObject;
var foo = "Changeable text";
var x = 0;
var y = 0;
var w = Screen.width;
var h = Screen.height/8;
function Update () {
fooBox = Instantiate(fooPrefab);
fooBox.GetComponentInChildren(UI.Text).text = foo;
fooBox.GetComponentInChildren(UI.Image).rectTransform.sizeDelta = new Vector2(w,h); // I need this in order to have a semi-transparent background
fooBox.GetComponentInChildren(UI.Text).rectTransform.sizeDelta = new Vector2(w,h);
fooBox.GetComponentInChildren(UI.Image).rectTransform.position = new Vector2(x,Screen.height-y);
fooBox.GetComponentInChildren(UI.Text).rectTransform.position = new Vector2(x,Screen.height-y);
}
This code works just fine. That is not the issue. But there's just so much code. There must be a better way. Any pointers?
Note: With fooPrefab the Text and Image are both children of the same game object, but even if I try to make one a child of the other, I still have to resize and move each one independently.
Your answer
Follow this Question
Related Questions
Change Text Scale on a Canvas Child from a script. 1 Answer
Snap UI Text inside canvas 1 Answer
Quest Script Help 2 Answers
stopping an ui element from moving if the y axis value is too low 0 Answers