Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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
1
Question by Tricell · Aug 30, 2016 at 01:37 AM · c#distance

Finding nearest game object

How do I find the nearest gameobject (or tag) and determine the distance between that object and the player?

clear explanation or C# only

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

3 Replies

· Add your reply
  • Sort: 
avatar image
8
Best Answer

Answer by b1gry4n · Aug 30, 2016 at 02:55 AM

If you have a lot of objects in your scene that you want to find the distance from but there are other objects you dont care about (for example: many enemies across the map, but you only want to get the enemies near the player) I would recomment using OnTriggerEnter to gather a list of nearby objects first.


You would do this by:

  • creating an empty game object as a child of your player

  • attaching a sphere collider and setting "trigger" to true

  • setting the radius to a "search radius" size determined by you

  • Attach a script to the object with OnTriggerEnter and do a check to determine if you care about this object (compare tag)

  • adding that object to a list.

  • OnTriggerExit remove that object from the list.

How to do this can be found here

You could also do a Physics.SphereCast invoking to obtain this list.


The next step would be to read from that list and find the closest object.

         Transform GetClosestEnemy (List<Transform> enemies, Transform fromThis)
         {
             Transform bestTarget = null;
             float closestDistanceSqr = Mathf.Infinity;
             Vector3 currentPosition = fromThis.position;
             foreach(Transform potentialTarget in enemies)
             {
                 Vector3 directionToTarget = potentialTarget.position - currentPosition;
                 float dSqrToTarget = directionToTarget.sqrMagnitude;
                 if(dSqrToTarget < closestDistanceSqr)
                 {
                     closestDistanceSqr = dSqrToTarget;
                     bestTarget = potentialTarget;
                 }
             }             
             return bestTarget;
         }

This will return the closest transform from the list you plug in. So you would need to manually call this function to do the check.

 closestEnemy = GetClosestEnemy (yourscript.yourtransformlist, this.transform);

Finding the distance from the closest enemy to the player is a simple Vector3.Distance

Comment
Add comment · Show 8 · 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 Adam_Benko · Jan 05, 2019 at 05:27 PM 0
Share

Hi. I dont understand one thing. closestEnemy = GetClosestEnemy (yourscript.yourtransformlist, this.transform);

yourtransformlist is "enemies" list from that script ? It does not work like that. Thanks.

avatar image Bonfire-Boy Adam_Benko · Jan 06, 2019 at 12:15 PM 1
Share

The enemies variable is local to the GetClosestEnemies function. Whatever you pass through when you call the function is referred to as enemies within that function, nowhere else.

What b1gry4n is suggesting that you pass through to it is the List of candidate objects that you've constructed using the method described in the second part of their answer.

As a first step, to see how it all works, you could try using Arkaid's answer to construct the list. So for example you could just try

closestEnemy = GetClosestEnemy( new List< GameObject > (GameObject.FindGameObjectsWithTag("Enemy")), this.transform );

This will be much less efficient but, depending on how often you make the call and how many objects you have, it might not matter too much.

One warning - if the object you're finding the distance from (the this in the call) has the same tag, then you'd either have to add something to the GetClosest function to make it ignore that object, or remove it from the list before passing it through. (otherwise it'd always just find itself - because the distance from itself is zero)

avatar image bryanhatami27 Bonfire-Boy · Nov 11, 2021 at 04:18 PM 0
Share

closestEnemy = GetClosestEnemy( new List (GameObject.FindGameObjectsWithTag("Enemy"), this.transform ); does not work because you cant turn new List into List

Show more comments
avatar image bryanhatami27 · Nov 12, 2021 at 01:31 PM 0
Share

closestEnemy = GetClosestEnemy( new List (GameObject.FindGameObjectsWithTag("Enemy"), this.transform );

does not work because it is trying to cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.List'

avatar image Bonfire-Boy bryanhatami27 · Nov 12, 2021 at 01:49 PM 0
Share

That code still has the error that I fixed yesterday (see comment above). You need a second closing bracket after ("Enemy"). I just checked the fixed code, it compiles for me.

avatar image Bonfire-Boy bryanhatami27 · Nov 12, 2021 at 02:01 PM 0
Share

Also worth noting that the error you're posting looks odd - it's saying "can't convert from X to X" when obviously no conversion would be needed as X=X.


It's possible that something's getting lost when you're copy-pasting the error message, due to the < and > not getting rendered in html. You can use back-quotes or code blocks to get around this.

avatar image
0

Answer by Arkaid · Aug 30, 2016 at 01:51 AM

20 seconds in google turn this up:

https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html

Second example. Not to bash, but search a bit before posting a question next time? :3~

Comment
Add comment · Show 7 · 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 Tricell · Aug 30, 2016 at 02:00 AM 0
Share

I've seen that. I've tried that. It doesn't work.

avatar image Arkaid Tricell · Aug 30, 2016 at 02:02 AM 0
Share

It should. The code is solid. You must have a bug somewhere.

avatar image Tricell Arkaid · Aug 30, 2016 at 02:15 AM 0
Share

There's no bug in my game. The issue with unity API documents, is the instructions or information can sometimes be very vague. The code may not have caused any errors, but nothing in the code seems to work, even when I print or use debug.log, I get nothing.

Looking back, I think the problem is that my version of Unity is different than the one in the example. But yes, I'v tried that and messed with that code several times...

Show more comments
avatar image mpbMKE · Jun 17, 2021 at 04:16 AM 0
Share

For anyone co$$anonymous$$g across this post via Google:

While the example from the Docs herein works, it's not exactly optimized. All "Find" operations are expensive, and "Find With Tag" requires passing string references which... sucks, to put it bluntly.

Personally, I don't love using the SphereCast in the green answer above, but if you already have your enemies collected in another way (such as having them all spawn into an empty and looping through that, for example), the principles of the rest of that solution should get you what you need.

avatar image Bonfire-Boy mpbMKE · Nov 16, 2021 at 01:57 AM 0
Share

To be fair, the accepted answer does actually involve collecting your list of enemies "in another way" - by adding/removing them to/from such a collection using a proximity trigger. That's only slightly different from what you're suggesting, and could be more efficient (it'd depend on the numbers). The references to SphereCast and (in the comments) Find functions are only there as examples of ways of collecting the objects using simpler (but yes, less efficient) code.

avatar image
0

Answer by studiomilk_ · Mar 15, 2020 at 07:43 PM

Hi, I wrote this 5 minutes ago and it works for me:

     minions = GameObject.FindGameObjectsWithTag("Minion");
     Vector3 shortestDistaceToMinion = new Vector3(1000, 1000, 1000);

     for (int i = 0; i < minions.Length; i++)
     {
         Vector3 distanceToMinion = transform.position - minions[i].transform.position;

         if (distanceToMinion.magnitude < shortestDistaceToMinion.magnitude)
         {
             shortestDistaceToMinion = transform.position - minions[i].transform.position;
             target = minions[i];
         }
     }
Comment
Add comment · Show 7 · 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 Bonfire-Boy · Mar 15, 2020 at 08:12 PM 0
Share

Sorry, but there is already an accepted answer which does the same thing better. It

- stores the shortest distance so far as a float not a vector (because that's what it is, and because it means you don't have to recalculate that shortest distance so far every time you go through the loop)
- initialises it to its largest possible value (more robust)
- compares square magnitude ins$$anonymous$$d of magnitude (more efficient)

You would be advised to alter your function so it looks more like the one above

avatar image studiomilk_ Bonfire-Boy · Mar 16, 2020 at 04:52 PM 1
Share

Thanks for your feedback but as I said, it works for me. Sometimes people who are still learning appreciate a simpler breakdown of a thing and care less about efficiency and robustness. You would be advised to keep that in $$anonymous$$d or better yet, don't discourage people who are trying to help.

avatar image Bonfire-Boy studiomilk_ · Mar 16, 2020 at 06:55 PM 2
Share

Sorry but on this site, you have to expect your answers to be critiqued.

Your version is not simpler, it's more complex. And what people who are still learning need are explanations of why one solution is better than another, which is what I provided.

Show more comments
avatar image hdihd9162 · Apr 14, 2020 at 04:17 AM 0
Share

can you send Definition of $$anonymous$$ions and target???

avatar image hdihd9162 · Apr 14, 2020 at 02:31 PM 0
Share

studiomilk_ can you send Definition of $$anonymous$$ions and shortestDistaceTo$$anonymous$$inion and target ??

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

220 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 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 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

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

How To Properly Return An Object If Within Distance Range? 1 Answer

Easiest way to find a length I need? 2 Answers

Only make connected rigidbody move when distance is changed on 2d joint 0 Answers


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