NullReferenceException: Object reference not set to an instance of an object

Hello everyone, I’m making a Pong clone right now and atm I am trying to make the score. Whats supposed to happen is that when you hit the right or left wall you score a point. But this error keeps popping up:

NullReferenceException: Object reference not set to an instance of an object
Ball.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/Ball.cs:53)

I’m using 2 scripts, here’s the first one:

using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {
public float speed = 30;

public GameManager gm;

void Start () 
{
	GetComponent<Rigidbody2D> ().velocity = Vector2.right * speed;

	GameObject g = GameObject.Find ("GM");
	GameManager gm = g.GetComponent<GameManager> ();
}

void OnCollisionEnter2D (Collision2D col)
{
	if(col.gameObject.name == "RacketLeft")
	{
		float y = hitFactor(transform.position, col.transform.position, col.collider.bounds.size.y);

		Vector2 dir = new Vector2 (1, y).normalized;

		GetComponent<Rigidbody2D>().velocity = dir * speed;
	}

	if (col.gameObject.name == "RacketRight") 
	{
		float y = hitFactor(transform.position, col.transform.position, col.collider.bounds.size.y);

		Vector2 dir = new Vector2 (-1, y).normalized;
		
		GetComponent<Rigidbody2D>().velocity = dir * speed;
	}
}

float hitFactor(Vector2 ballPos, Vector2 racketPos, float racketHeight)
{
	return(ballPos.y - racketPos.y) / racketHeight;
}

void OnTriggerEnter2D (Collider2D other)
{
	if(other.gameObject.CompareTag("WallR"))
	{
		gm.countL += 1;
		gm.SetCountText();
	}

	if(other.gameObject.CompareTag("WallL"))
	{
		gm.countR += 1;
		gm.SetCountText();
	}
}

}

Here’s the second one:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class GameManager : MonoBehaviour {

public Text rScore;
public Text lScore;
//public Text roundWinner;

/*
public GameObject ball;
public GameObject ballSpawn;
*/

public int countR;
public int countL;

void Start () 
{
	countR = 0;
	countL = 0;
	//roundWinner.text = "";
	SetCountText ();
}

public void SetCountText()
{
	rScore.text = "" + countR.ToString ();
	lScore.text = "" + countL.ToString ();
}

/*
void SetCountTextL ()
{

}
*/

}

Thanks in advance :slight_smile:

in future please format ALL of your code - the error messages contain line numbers which won’t match up if you don’t…

your problem relates to the scope of the gm variables. i use variables and not variable because in Start() you’ve defined gm, which is NOT the same one that the rest of your code is using…