So I have my player shoot fireballs that go towards the closest enemy. It works all fine and well but after all enemies are killed in the scene, I get a Missing Reference Exception saying “The object of type ‘GameObject’ 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.”.
How should I check if it’s null?
My script:
public float speed = 2f;
public float minDistance = 0f;
private float range;
GameObject[] Targets;
GameObject TargetToFind;
private GameObject player;
float curDist = 1;
void Start()
{
player = GameObject.Find("Player");
}
void Update ()
{
Targets = GameObject.FindGameObjectsWithTag("Enemy");
curDist = int.MaxValue;
foreach (GameObject item in Targets)
{
float dist = (player.transform.position - item.transform.position).sqrMagnitude;
if (dist < curDist)
{
curDist = dist;
TargetToFind = item;
//print (dist);
}
}
range = Vector2.Distance (transform.position, TargetToFind.transform.position);
if (range > minDistance) {
transform.position = Vector2.MoveTowards (transform.position, TargetToFind.transform.position, speed * Time.deltaTime);
}
}
}