- Home /
Trying to get javascript to chnge UI.text but it wont
I am trying to change the text field of a UI but it won't let me.
I am using javascript
There is a canvas and the text field is on the canvas.
I have a variable 'textField' which is a UI.text on the script.
I dragged the proper game object onto it.
It gives an error when it tries to access the text field. NullReferenceException: Object reference not set to an instance of an object Score_js.Update () (at Assets/Scripts-JS/Scripts-GUI/Score_js.js:33)
/////////////////////////////////////////////////////// #pragma strict import UnityEngine.UI; /////////////////////////////////////////////////////// //VARIABLES static var numHits:int = 0; static var playerScore:int = 0;
var textField : UI.Text; var str1:String = ""; /////////////////////////////////////////////////////// function Start() { if (playerScore < 0) { playerScore = 0; } str1 = playerScore.ToString(); textField = GetComponent(UI.Text); textField.text = str1; } /////////////////////////////////////////////////////// function Update () { if (playerScore < 0) { playerScore = 0; } str1 = playerScore.ToString(); textField = GetComponent(UI.Text); textField.text = str1; } ///////////////////////////////////////////////////////
Answer by OncaLupe · Nov 13, 2015 at 06:22 PM
Remove the textField = GetComponent(UI.Text);
lines. That code is if you need to get the UI.Text component that's on the same object as the script. Since the textField variable is public and you dragged the item into it, it's already set and there's no reason to try and set it again. Also, since the object the script is on doesn't have a UI.Text component, that returns null and you've lost the reference.
Answer by RandomCharacters · Nov 13, 2015 at 06:24 PM
I figurered it out. Thanks /////////////////////////////////////////////////////// #pragma strict import UnityEngine.UI; /////////////////////////////////////////////////////// //VARIABLES static var numHits:int = 0; static var playerScore:int = 0;
var textField1 : UI.Text;
var textField2 : UI.Text;
var str1Score:String = "";
///////////////////////////////////////////////////////
function Start()
{
if (playerScore < 0)
{
playerScore = 0;
}
str1Score = playerScore.ToString();
textField2 = textField1.GetComponent(UI.Text);
textField2.text = str1Score;
}
///////////////////////////////////////////////////////
function Update ()
{
if (playerScore < 0)
{
playerScore = 0;
}
str1Score = playerScore.ToString();
textField2 = textField1.GetComponent(UI.Text);
textField2.text = str1Score;
}
///////////////////////////////////////////////////////