Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
This question was closed Sep 24, 2013 at 09:34 AM by Fattie for the following reason:

Duplicate Question

This post has been wikified, any user with enough reputation can edit it.
avatar image
0
Question by Bman3601 · Sep 24, 2013 at 01:52 AM · destroyarraysremovemissingreferenceexception

Remove dead enemies from array

Hello everyone. I'm working on a script that is meant to get all of the game objects in the scene that are tagged "Enemy", and then get the closest one to the player. When the enemy is killed and destroyed, the script gives me a missing reference exception error. I've tried searching up several possible solutions, such as checking if the enemy is null, but when I try them it usually gives me a warning that states "This method could return default value implicitly." at (13, 10). Being still very new to unity and things such as lists and arrays, I am unsure how to go about removing an enemy from the array when it is killed without running into these errors. Any helpful advice and references are much appreciated.

Here is the Script :

 #pragma strict
 var player : Transform;
 
 
 var enemyNear : boolean;
 
 
 var targetedEnemy : GameObject;
 var closest : GameObject;
 var gos : GameObject[];
 gos = GameObject.FindGameObjectsWithTag("Enemy");
 
 function FindClosestEnemy() : GameObject
 {
  
  var distance = Mathf.Infinity;
  
  for (var go : GameObject in gos)
  {
      var enemyHealth : EnemyHealth;
      enemyHealth = go.GetComponent(EnemyHealth);
      
      if(enemyHealth.dead == true)
      {
          Destroy(go, 3);
      }
      
      if(go != null){
   var diff = (go.transform.position - player.position);
   var curDist = diff.sqrMagnitude;
    if(curDist < distance) 
    {
     closest = go;
     distance = curDist;
    }
   
              }
  return closest;
  
  }
  }
 
 
 function EnemyNear()
 {
  if(Vector3.Distance(closest.transform.position, player.position) < 10)
   {
    enemyNear = true; 
   } 
  else{
    enemyNear = false;
   }
 }
 
 
 
 function Start () {
  targetedEnemy = null;
  FindClosestEnemy();
 }
 
 function Update () {
  EnemyNear();
  FindClosestEnemy();
  gos = GameObject.FindGameObjectsWithTag("Enemy");
  
 }
 

This is the portion of the EnemyHealth script that the previous script accesses :

 function Dead(){
  if(currentHealth <= 0){
   currentHealth = 0;
   dead = true;
  }
  else{
   dead = false;
  }
 
 }
 

When the enemy is killed, two missing reference exceptions show up, one at line 46, and one at line 63. Sorry if my post got a little lengthy, thanks for your time.

Comment
Add comment · Show 2
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
avatar image Fattie · Sep 24, 2013 at 09:34 AM 1
Share

Do not use arrays. Generally, as a beginner always and every time use List.

avatar image Dag-Tholander · Jun 15, 2015 at 12:46 PM 0
Share

Hi! I know this is an old thread, but I just had the problem myself and figured out a way to solve it :

    //del = the object to destroy
 //Enemies is a "List" of GameObjects
 //Import "Lists" by putting "Using System.Collections.Generic;" at the top of your script
 
      void Update (){
         
             for (var del = 0; del < Enemies.Count; del ++) {
 
                 if(Enemies[del].gameObject == null){
                     Enemies.RemoveAt(del);//Remove "Dead" enemy
               }
             }
         }

I hope this helps!

1 Reply

  • Sort: 
avatar image
2
Best Answer

Answer by clunk47 · Sep 24, 2013 at 02:03 AM

I would tell you to have the array defined in Update(), so that it always contains only what you tell it to, but I would be giving bad advice. However, I do have good advice. Do some homework on System.Collections.Generic.List, and List.Remove. Also have a look at RemoveAt.

Here's an example in C# on how to remove an item from a generic list. In this example you'll need to tag some objects in your scene "Enemy". When you hit the spacebar, the first index will be removed each time.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class example : MonoBehaviour
 {
     public List<GameObject> enemies;
     
     void Awake()
     {
         enemies = new List<GameObject>();
         foreach(GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
         {
             enemies.Add (enemy);    
         }
     }
     
     void Update()
     {
         if(enemies.Count > 0)
         {
             if(Input.GetKeyDown (KeyCode.Space))
             {
                 enemies.RemoveAt(0);
                 print (enemies.Count);
             }
         }
     }
 }




Comment
Add comment · Share
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

Follow this Question

Answers Answers and Comments

17 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

Related Questions

MissingReferenceException? 1 Answer

Removing music gameobject when no-longer wanted. 1 Answer

Removing from a list 1 Answer

Check If Component is Requred by Another 1 Answer

How do I destroy a specific clone of a GameObject? 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