NullReferenceException when attempting to access a method in another script.

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.

Sorry, first answer has been eaten by the system. Here again:

You need a connection from the ForceField-Script to the Score-Script.

I assume, that the score script is a Component of the same game object as the force field.

In the Start() method of ForceField, get a reference to the Score-Script:

    private Score m_Score;
    
    void Start()
    {
        m_Score = GetComponent<Score>();
        if (m_Score == null)
        {
            Debug.Error("Score not found.");
        }
    }

After that, you can access the Score with m_Score.UpdateScore(…).

If the script is on another gameObject (e.g. the player), you have to grab the player first:

    void Start()
    {
        GameObject player = GameObject.FindWithTag("Player");
        m_Score = player.GetComponent<Score();
    }

Hope that helps.