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 HDZD · Sep 03, 2016 at 01:31 PM · objectnot workingtagclosest

Problem with choosing the closest game object

Hello, i'm kind of new here so i need some help, any hints would be appreciated. :) i have this code that looks for the closest game object tagged with enemy, and sets that as the object closestenem for later use. the problem is, after the code finds the closest object tagged with enemy for the second time, it doesn't update the closestenem object. i tried moving the code to FixedUpdate but it didnt help at all. here is the code i'm using :

 void Update () {
     enemy = GameObject.FindGameObjectsWithTag ("enemy");
     //finding the closest enemy
     foreach (GameObject enem in enemy) {
         tempdist = Vector3.Distance (transform.position,enem.transform.position);
         if (tempdist < distance) {
             closestenem = enem;
             distance = tempdist;
         }
     }
 }
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
1
Best Answer

Answer by flashframe · Sep 03, 2016 at 02:20 PM

You need to reset the distance on each frame, since you're only interested in the closest enemy for this frame, not for all time.

 void Update()
 {
     FindClosestEnemy();
 }
 
 void FindClosestEnemy()
 {
     enemies = GameObject.FindGameObjectsWithTag ("enemy");
     float distance = 100f; // Any large number will do as long as it's further than any enemy could be
     foreach (GameObject e in enemies) {
         float tempdist = Vector3.Distance (transform.position,e.transform.position);
         if (tempdist < distance) {
             closestEnemy = e;
             distance = tempdist;
         }
     }
 }

If the amount of enemies never changes, I'd also recommend only finding them at the start to avoid calling FindObjectsWithTag every frame.

 GameObject[] enemies;
 GameObject closestEnemy;
 
 void Start()
 {
     enemies = GameObject.FindGameObjectsWithTag ("enemy");
 }
 
 void Update()
 {
     FindClosestEnemy();
 }
 
 void FindClosestEnemy()
 {
     float distance = 100f; // Any large number will do as long as it's further than any enemy could be
     foreach (GameObject e in enemies) {
         float tempdist = Vector3.Distance (transform.position,e.transform.position);
         if (tempdist < distance) {
             closestEnemy = e;
             distance = tempdist;
         }
     }
 }

If the number of enemies does change, you could consider creating an object pool. https://unity3d.com/learn/tutorials/topics/scripting/object-pooling

And finally, instead of calling this function in Update, you could run a Coroutine and check for the closest enemy less often. It depends on how precise it needs to be.

 IEnumerator FindClosestEnemy()
 {
     while(true)
     {
         float distance = 100f; // Any large number will do as long as it's further than any enemy could be
         foreach (GameObject e in enemies) {
             float tempdist = Vector3.Distance (transform.position,e.transform.position);
             if (tempdist < distance) {
                 closestEnemy = e;
                 distance = tempdist;
             }
         }
         yield return new WaitForSeconds(0.1f); //update as often as you like
     }
 }

Comment
Add comment · Show 2 · 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 HDZD · Sep 03, 2016 at 02:39 PM 0
Share

Thank you so much for your answer it helped a lot ! right now, i fixed the problem thanks to your help while keeping the functions in the Update event. I will try to use the object pool solution soon, as i need some time to learn how to use it, but it looks like a perfect solution ! Thank you!

avatar image flashframe HDZD · Sep 03, 2016 at 02:48 PM 0
Share

You're welcome, glad you got it working. Definitely check out object pools when you get the chance :-)

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Need help to understand Unity's logic or C# ? 1 Answer

UI Scroll View object is not moving 0 Answers

Get closest gameobject in each direction 1 Answer

How can I find a point on a collider that is closest to my player. 0 Answers

How is this done with UNİTY ? 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