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!
m0guz
2
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();
}