I want to print the message which I have previously declared as an array. This is my code:-
var an = new Array();
an[0] = "Message1";
function OnGUI()
{
GUI.Label(Rect(0.8*Screen.width,0.12*Screen.height,0.1*Screen.width,0.5*Screen.height),an[0]);
}
What have I done wrong here, in printing the message? Can someone tell me? Thanks in advance.
You didn’t tell us what errors you’ve got, but I suppose your problem is the undefined type of an: the Array class creates an untyped array, and GUI.Label must know the argument type to select the right version (string, texture etc.). You could do the following:
function OnGUI(){
var a: String = an[0]; // copy the array element to a string variable
GUI.Label(Rect(0.8*Screen.width,0.12*Screen.height,0.1*Screen.width,0.5*Screen.height), a);
}
But a better solution would be to avoid the Array class: it’s way slower than the builtin arrays, and due to its untyped nature always give us a lot of headaches. You could declare a public String array and assign your messages to it in the Inspector, like this:
var an: String[]; // assign your messages at the Inspector
function OnGUI(){ // no need to use a string variable, since an is a string array
GUI.Label(Rect(0.8*Screen.width,0.12*Screen.height,0.1*Screen.width,0.5*Screen.height), an[0]);
}