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);
}
}