object reference not set to an instance of object

Hello,
I am trying to write a script for breakout game. I have a hud script which is attached to UI canvas. This script is used to update score and balls left to play.

public class HUD : MonoBehaviour
{
   
    static Text scoretext;
    static float actualscore = 0;
    static Text ballsleft;
    static float actualballsleft = ConfigurationUtils.NumberOfBallsPerGame;
    public static  void blockhit()
    {
        actualscore += 1;
        scoretext.text = "Score: " + actualscore.ToString();

    }
    public static void ballsleftmethod()
    {
        actualballsleft -= 1;
        ballsleft.text = "Balls Left: " + actualballsleft.ToString();
    }

    // Start is called before the first frame update
    void Start()
    {
        Text scoreetext = GameObject.FindGameObjectWithTag("score").GetComponent<Text>();
        scoreetext.text = "Score: " + actualscore.ToString();
        Text balleslefttext = GameObject.FindGameObjectWithTag("ballsleft").GetComponent<Text>();
        balleslefttext.text = "Balls Left: " + actualballsleft.ToString();
    }

I have another script named block which is attached to each block in the game that’s going to hit.

public class block : MonoBehaviour
{void OnCollisionEnter2D(Collision2D collision)
       
    {
        GameObject collider = collision.gameObject;
        if (collider.CompareTag("Ball"))
        {
           HUD.blockhit();
            Destroy(gameObject);
           
        }
    }

I am trying to call blockhit() method in the from the HUD script but getting error
“NullReferenceException: Object reference not set to an instance of an object
block.OnCollisionEnter2D (UnityEngine.Collision2D collision)” . Any help would be greatly appreciated!!

When you click the error, what line does it go to?

Nevermind, I see the issue.

in HUD, you have a static variable called “scoretext”, which blockhit() depends on. When it tries to access this variable, scoretext is null.

Why is scoretext null? Because in Start, you’ve found the object you want but then assigned it to a local variable named “scoreetext”. “scoretext” has never been assigned.

1 Like

it goes to line 12 on HUD script

scoretext.text = "Score: " + actualscore.ToString();

Yup, as I thought. See second reply ^

Thanks alot that worked!!