Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by Yoshinator2 · Nov 27, 2016 at 07:25 AM · gameobjectobjectdistancelistsmissing

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.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

96 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges