In my code I have a script called “Forcefield” that keeps track of how many times it has been hit. The int variable keeping track of this is called “timesHit.” I am currently trying to keep track of the user’s score, so all I need to do is set the score text to whatever timesHit is currently at. To keep the score constantly updating, I have the method in the scrip that is attached to the score text being called with the changing timesHit variable.
Here is my OnCollisionEnter2D() method for my Forcefield script:
int timesHit = 0;
public Score score;
void OnCollisionEnter2D(Collision2D collision)
{
timesHit++;
score.updateScore (timesHit);
}
Here is my Score script containing the update method:
public class Score : MonoBehaviour
{
public Text score;
void Start()
{
score.text = "Score: 0";
}
public void updateScore(int timesHit)
{
score.text = string.Format ("Score: {0}", timesHit);
}
}
Everything that I have found online has failed me so far. I currently have it setup as I drag and dropped the score text into my Score script reference. When the start method is called in Score, it works fine. After that I get the nullReferenceException: Object reference not set to an instance of an object.