- Home /
Problem with type Text: null reference
Hi, I have this code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Puntos: MonoBehaviour {
public Text textScore;
public int score = 0;
public void Start(){
textScore.text = "Score: " + score;
}
public void AddPoints(int add){
score += add;
textScore.text = "Score: " + score;
}
}
Then, in another class I have:
private Puntos p = new Puntos();
p.AddPoints(5);
Why does Unity shows me a NullReference error when I call "AddPoints" method (it breaks when I try to set the new Text...) ? I can't understand how it fails there, if when I initialize the
private Puntos p = new Puntos();
I have the same piece of code.
Thanks in advance!
Answer by m0guz · Nov 29, 2015 at 07:19 PM
When you are creating a new Puntos object named p, you are not referencing any Text object to textScore.
Your code should be something like this;
public void Start()
{
textScore = GameObject.Find("textScoreinCanvas").GetComponent<Text>();
textScore.text = "Score: " + score.ToString();
}
That was! Thank you, I don't know how to initialise or attach the objects I have declared in my script to those which I have already created visually properly yet.
Your answer
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
How to align text? 1 Answer
Text doesn't appear when i add it via script 1 Answer
Why is it that whenever i load a new scene while playing some of my linked texts dont work???? 1 Answer
How to add terms and conditions policy in unity android app? 1 Answer