Trying to fix an error.

So I’m playing around with unity. I have a cube that when it collides with another cube it will be destroyed and then show a text that says game over, but i keep getting this error and i don’t know how to fix it.

MissingReferenceException: The object of type ‘Text’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

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

public class dd : MonoBehaviour
{
    private Vector3 screenPoint;
    private Vector3 offset;
    private int count;
    public Text gameOverText;
   
    void Start()
    {
        gameOverText.gameObject.SetActive(false);
       
    }
    void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));

    }

    void OnMouseDrag()
    {
        Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
        transform.position = cursorPosition;
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.name == "block")
        {
            Destroy(gameObject);
        }
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        Destroy(gameObject);
    }

    void OnDestroy()
    {
        gameOverText.gameObject.SetActive(true);
    }

    public void OnBecameInvisible()
    {
        Destroy(gameObject);
    }


}

As the error says, your Text (gameOverText) is being destroyed and afterwards being accessed.
Which line throws the error (generally nice to know)? And is this your only script? Because it doesnt seem like you are destroying the Text object here, so it may be externally destroyed before you try to access it.

Your OnDestroy() method looks problematic. Whenever you change scenes your OnDestroy() will be called, but everythhing else in your scene will also get destroyed during a scene change, likely including gameOverText.

But I’d look at everywhere you are potentially destroying gameOverText and see if that code could be called prior to trying to access it. Then either just don’t destroy it early, or don’t access it after it has been destroyed.