Missing GameObject, help!!
I'm making a 2D game where there are enemies around and have made a script to find the closest enemy/player with the tag. It works perfectly. However, whenever one of the enemies is killed, it destroys the gameObject in the enemys' controller script as it should. The problem is whenever this happens if the enemy is the closest target, the console blares errors like this:
MissingReferenceException: 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. findNearestTarget.GetClosestEnemy (System.Collections.Generic.List`1 enemies, UnityEngine.GameObject fromThis) (at Assets/Scripts/findNearestTarget.cs:120) findNearestTarget.Update () (at Assets/Scripts/findNearestTarget.cs:23)
In the inspector it also says the the gameObject is missing. This was expected, however, the code does not seem to change the closestEnemy to anything even when something is closer than the last enemy. It stays on Missing and spams the error above. Any ideas? Here is my code:
public class findNearestTarget : MonoBehaviour { //Creates a list that contains all of the enemy gameObjects within the circle collider List enemies = new List(); //Is the closest gameObject with the specified tag. public GameObject closestEnemy; // Use this for initialization void Start() {
}
// Update is called once per frame
void Update()
{
//Finds the closest object with the specific tag each frame.
//It sends the enemies list component and this game object
closestEnemy = GetClosestEnemy(enemies, this.gameObject);
Debug.Log("The closest enemy is at: " + closestEnemy.gameObject.transform.position);
}
//Will run when anything goes into the circle collider
public void OnTriggerEnter2D(Collider2D other)
{
//Checks to see if the object that is in the collider has the specified tag
if (other.tag == "Player")
{
//Sets the inital value to zero, only needed for the debug.
int i = 0;
//Will run if the gameObject is not already in the list
if (!enemies.Contains(other.gameObject))
{
//Adds the gameObject to the list
enemies.Add(other.gameObject);
}
//Will run while the i value is less than the amount of gameObjects in the list
while (i < enemies.Count)
{
//Tells you the gameObject added and the current position.
Debug.Log("Number " + i + "position is: " + enemies[i].transform.position);
//Adds 1 to i
i++;
}
}
//Checks to see if the object that is in the collider has the specified tag
if (other.tag == "Enemy")
{
//Sets the inital value to zero, only needed for the debug.
int i = 0;
//Will run if the gameObject is not already in the list
if (!enemies.Contains(other.gameObject))
{
//Adds the gameObject to the list
enemies.Add(other.gameObject);
}
//Will run while the i value is less than the amount of gameObjects in the list
while (i < enemies.Count)
{
//Tells you the gameObject added and the current position.
Debug.Log("Number " + i + "position is: " + enemies[i].transform.position);
//Adds 1 to i
i++;
}
}
}
public void OnTriggerExit2D(Collider2D other)
{
//Checks to see if the object that is in the collider has the specified tag
if (other.tag == "Player")
{
//Will run if the gameObject IS in the list
if (enemies.Contains(other.gameObject))
{
//Removes the gameObject from the list
enemies.Remove(other.gameObject);
}
}
//Checks to see if the object that is in the collider has the specified tag
if (other.tag == "Enemy")
{
//Will run if the gameObject IS in the list
if (enemies.Contains(other.gameObject))
{
//Removes the gameObject from the list
enemies.Remove(other.gameObject);
}
}
}
//Gets the information, and will return the bestTarget variable. This takes in the listComponenet
//and enemies list, and the gameObject which is this.gameObject in the calling function.
GameObject GetClosestEnemy(List<GameObject> enemies, GameObject fromThis)
{
int i = 0;
while (i < enemies.Count)
{
if(enemies[i] == null)
{
enemies.Remove(enemies[i]);
}
//Adds 1 to i
i++;
}
//Makes it have to find a new bestTarget by setting it to nonexistent
GameObject bestTarget = null;
//Sets the closestDistanceSqr to infinity, making any number smaller than it for the
//function below.
float closestDistanceSqr = Mathf.Infinity;
//sets the currentPosition to be the fromThis gameObjects position
Vector3 currentPosition = fromThis.gameObject.transform.position;
//Will run for each gameObject that is in the enemies list. The gameObjects are given
//the name potentialTarget each time it runs through.
foreach (GameObject potentialTarget in enemies)
{
Debug.Log("Ok");
//Gets the distance from the current position to the potentialTarget position
Vector3 directionToTarget = potentialTarget.gameObject.transform.position - currentPosition;
//Squares the Magnitude, saving ram somehow IDK
float dSqrToTarget = directionToTarget.sqrMagnitude;
//Will run if the dSqrToTarget is smaller than the closestDistance
if (dSqrToTarget < closestDistanceSqr)
{
//Sets the closest distance to be the distance squared to the target
closestDistanceSqr = dSqrToTarget;
//Sets the bestTarget to be the potentialTarget
bestTarget = potentialTarget;
}
}
//Returns with the bestTarget GameObject, which above is the closestEnemy variable.
return bestTarget;
}
}
Please note that line 120 is:
Vector3 directionToTarget = potentialTarget.gameObject.transform.position - currentPosition;
And line 23 is:
closestEnemy = GetClosestEnemy(enemies, this.gameObject);
Please help, it took me all day to write this script and I am already very frustrated. Sorry for the long question! Thanks.
Your answer
Follow this Question
Related Questions
Player Can't hit enemy 0 Answers
How to Access Values from a Object,How to access values from a object 0 Answers
Get the lowest value from a Gameobject List 0 Answers
Game works on most computers but half the scene vanishes on one of them. 1 Answer
ERROR CS0029: Cannot implicitly convert type `UnityEngine.GameObject' to `TriggerSphere' 1 Answer