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 /
avatar image
0
Question by jhunglow · Jul 01, 2015 at 09:54 AM · gameobjectvector3distance

How do you find the distance of multiple objects in a array

I am trying to find the distance of multiple enemys in the scene but the code i have only works for one of the enemys then when the other enemys try to attack it does not do any damage. When the one zombie that the code calculates the distance for is destroyed and the other zombies try to attack this error message pulls up:

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.

This is my code:

using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic;

public class FPS_Health : MonoBehaviour { public int count; public Text health; public int ammo_count; public Text ammo; public GameObject bullet; public float dist;

 public float time;
 public GameObject ammo_weapon;
 private AudioSource reload;
 public AudioClip reload_weapon;
 Transform enemy;
 public GameObject player_reload;
 public GameObject[] zombie;//The array of zombies (enemys)
 public void Start()
 {
     reload = player_reload.GetComponent<AudioSource> ();

     zombie =  GameObject.FindGameObjectsWithTag("zombie");

     time = 2;
     ammo_count = 100;
     count = 100;
 }
 public void Update()
 {

     foreach (GameObject zombies in zombie) {
         dist = Vector3.Distance(zombies.transform.position, transform.position);//only calculates the distance of one of the enemys not all of them
     }
 
     if (dist <= 2) {
         time -= 1 * Time.deltaTime;
     }
     if (time <= 0) {
         count = count - 10;
         SetCountText();
         time = 2;
     }

     if (Input.GetKey (KeyCode.Escape)) {
         Application.LoadLevel ("Menu");
     }
     if (Input.GetKey (KeyCode.R)) {
         Application.LoadLevel(Application.loadedLevel);
     }
     if (count <= 0) {
         Application.LoadLevel (Application.loadedLevel);
     } else if (count >= 100) {
         count = 100;
     }
     if(Input.GetButtonDown("Fire1"))
        {
         ammo_count = ammo_count - 1;
         SetCountText();
     }
     if (ammo_count < 0) {
         ammo_count = 0;
         bullet.SetActive (false);
     } else if (ammo_count > 0) {
         bullet.SetActive(true);
     }


 }

     void OnCollisionEnter (Collision col)
     {
     if (col.gameObject.name == "zombie_normal 1 2") {
         count = count - 10;
         SetCountText();
     }
     if (col.gameObject.name == "ammo") {
         ammo_count = ammo_count + 25;
         SetCountText();
         Destroy(col.gameObject);
         reload.Play ();

     }
     if (col.gameObject.name == "Health") {
         count = count + 10;
         SetCountText();
         Destroy(col.gameObject);
     }


 
 }
 void OnTriggerEnter(Collider other)
 {
     if(other.gameObject.tag == ("ammo"))
        {
         ammo_count = ammo_count + 25;
         SetCountText();
         Destroy(other.gameObject);

     }
 }

 
     
 
     void SetCountText ()
     {
         health.text = "Health: " + count.ToString ();
         ammo.text = "Ammo: " + ammo_count.ToString ();
     }

 }


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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by NeverHopeless · Jul 01, 2015 at 10:28 AM

Here, you overwrites the previously calculated distance dist and ends up keeping the last one:

  foreach (GameObject zombies in zombie) {
      dist = Vector3.Distance(zombies.transform.position, transform.position);//only calculates the distance of one of the enemys not all of them
  }

So your code should look like:

  foreach (GameObject zombies in zombie) {
      dist = Vector3.Distance(zombies.transform.position, transform.position);//only calculates the distance of one of the enemys not all of them
      if (dist <= 2) {
         time -= 1 * Time.deltaTime;
      }
      if (time <= 0) {
         count = count - 10;
         SetCountText();
        time = 2;
      }
  }
  //... Rest of the Update() code

Regarding error message:

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.

Once you do a Destroy() Destroy(other/col.gameObject); you should check this object other/col.gameObject in zombie[] array and remove it from the array too. So on next iteration of Update() the deallocated object will be excluded from for loop:

foreach (GameObject zombies in zombie) { ... }

Hope it helps!

Comment
Add comment · Show 4 · 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
avatar image jhunglow · Jul 01, 2015 at 02:22 PM 0
Share

How would i check to see if it is destroyed and remove it from the array?

avatar image NeverHopeless · Jul 01, 2015 at 03:10 PM 0
Share

using OnTriggerEnter and OnCollisionEnter functions. When these events raises you can get the game object.

avatar image Bampf · Jul 01, 2015 at 03:24 PM 0
Share

You wrote: "When the one zombie that the code calculates the distance for is destroyed.." The same code that destroys the zombie needs to remove it from the array. Tip: I'm guessing the FPS_Health class is not the one that destroys the zombie. But the zombie array is in the FPS_Health class for some reason. Two ways to handle this: either move the zombie array out of FPS_Health, or, when a zombie dies, broadcast a message to all game objects to let them know. Then each object can do whatever they want about it (FPS_Health would remove that zombie from its array.)

avatar image jhunglow · Jul 01, 2015 at 06:23 PM 0
Share

So what would the code look like because i cant seem to find what i need to type in order to remove the gameobject from the array

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Finding Nearest Object Both Positive And Negative? 1 Answer

Help with distance between multiple objects 3 Answers

how do i fix my script in the content below? 0 Answers

Find gameobject furthest from player along z axis 0 Answers

Distance between a gameObject and a direction vector. 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