- Home /
The question is answered, right answer was accepted
Finding a GameObject using a canvas text?
I just don't understand it. I used to use guitext and managed to muddle through with that. I've got a canvas, called "Canvas" and a text ui element called "text" – think these are the defaults.
With javascript, I just want to be able to affect the value of the text shown. How do I do this? I've googled and tried to use their examples, but I either get an error of just nothing happens.
Please help. Tearing my hair out over what should be so, so so simple.
Not solved. What I'm trying to do is to find a gameobject (in this case, text with a specifc name in a canvas).
var myDescText : GameObject;
myDescText = GameObject.Find("NotifyText");
// for the purposes of this question, the variable myLitem contains a string "redmist"
// so, with this line, the text of the gameObject called 'NotifyText' should be changed to 'redmist' right?
myDescText.GetComponent <Text> ().text = myLitem;
Except it doesn't work and spits out 3 errors all pointing to the last line of my code. These errors are:
Assets/scripts/switchscript.js(65,35): BCE0043: Unexpected token: ).
Assets/scripts/switchscript.js(65,36): BCE0044: expecting ), found '.'.
Assets/scripts/switchscript.js(65,37): UCE0001: ';' expected. Insert a semicolon at the end.
Please can someone see where I'm going wrong and offer corrections as needed.
There isn't enough context here to deter$$anonymous$$e what's wrong. You have a syntax error somewhere. Can you post the code near line 65?
You are using Javascript (unityScript) it does not contain a generic version of GetComponent.
myDescText.GetComponent (Text).text = myLitem;
Thanks fafase. So, what do I need to use ins$$anonymous$$d in unityscript/javascript?
Just to clarify bshalke, I've started afresh with a new script, which throws the errors.
pragma strict
var myDescText : GameObject; myDescText = GameObject.Find("NotifyText");
function Start () { myDescText.GetComponent ().text = "testing"; }
function Update () {
}
Throws the errors:
Assets/scripts/textscript.js(7,33): BCE0043: Unexpected token: ). Assets/scripts/textscript.js(7,34): BCE0044: expecting ), found '.'. Assets/scripts/textscript.js(7,35): UCE0001: ';' expected. Insert a semicolon at the end.
Answer by fafase · Oct 27, 2015 at 07:26 AM
You can use Javascript but just use it right.
var myDescText : GameObject;
function Start () {
myDescText = GameObject.Find("NotifyText");
if(myDescText != null){
var text : Text = myDescText.GetComponent (Text);
if(text !=null){
text.text = "testing";
}
}
}
The null checks are not required but you can also add some debug to see if something goes wrong.
Answer by KillHour · Oct 26, 2015 at 09:46 AM
The "Text" component has a property called "text"
That's the one you need to change.
var myTextObject : GameObject;
//Assign your object
myTextObject.GetComponent <Text> ().text = "Your text here."