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 Red Owl Games · Jan 13, 2016 at 02:15 PM · c#componentclosest

Allpurpose Function that finds closest GameObject with Component X

Hello!

I had a piece of code checking for the closest GameObject that has Component "Food" attached. Like this:

 GameObject[] allobjects=(GameObject[])GameObject.FindObjectsOfType<Food>();
 float closestdis=Mathf.Infinity;
 GameObject closestFood=null;
 foreach (GameObject t_object in allobjects) {
     float dis=(transform.position-t_object.transform.position).magnitude;
     if(dis<closestdis) {
         closestdis=dis;
         closestFood=t_object;
     }
 }

which worked fine. Now, I wanted to check for the closest GameObject that has the Component "Creature" attached. As this is more or less the same but with a different Component type, I tried to write a function that could find the closest GameObject with Component "x" attached. This function:

 GameObject FindClosest (Type _component) {
     GameObject[] allobjects=(GameObject[])GameObject.FindObjectsOfType(_component);
     float closestdis=Mathf.Infinity;
     GameObject closest=null;
     foreach (GameObject t_object in allobjects) {
         float dis=(transform.position-t_object.transform.position).magnitude;
         if(dis<closestdis) {
             closestdis=dis;
             closest=t_object.gameObject;
         }
     }
     return closest;
 }

which is called by doing this:

 GameObject closestfood=FindClosest(Food);

However, this doesn't work. Is what I want possible or do you have to copy and paste this code for every different ComponentType?

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

2 Replies

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

Answer by Bonfire-Boy · Jan 13, 2016 at 02:38 PM

If you're thinking about copying and pasting a bunch of code, just changing a type each time, chances are you want to be using Generics. Something like this...

 GameObject FindClosest <TComponent>() where TComponent : MonoBehaviour
 {
      GameObject[] allobjects=(GameObject[])GameObject.FindObjectsOfType< TComponent>();
      float closestdis=Mathf.Infinity;
      GameObject closest=null;
      foreach (GameObject t_object in allobjects) {
          float dis=(transform.position-t_object.transform.position).magnitude;
          if(dis<closestdis) {
              closestdis=dis;
              closest=t_object.gameObject;
          }
      }
      return closest;
  }

You'd call it using lines like

GameObject closestFood = FindClosest< Food >();

Comment
Add comment · Show 1 · 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 Red Owl Games · Jan 13, 2016 at 10:04 PM 0
Share

Awesome! This works perfectly. I rewrote the code to include a check if it doesn't find itself as closest, giving this a final (generic) way to solve this problem:

 GameObject FindClosest<TComponent>() where TComponent : $$anonymous$$onoBehaviour {
         TComponent[] allobjects=GameObject.FindObjectsOfType<TComponent>();
         float closestdis=$$anonymous$$athf.Infinity;
         GameObject closest=null;
         foreach (TComponent t_object in allobjects) {
             float dis=(transform.position-t_object.transform.position).magnitude;
             if(dis<closestdis && !(t_object.gameObject==this.gameObject)) {
                 closestdis=dis;
                 closest=t_object.gameObject;
             }
         }
         return closest;
     }

Which is called with the line:

 GameObject closestFood = FindClosest<Food>();

An alternative is to return the component ins$$anonymous$$d of the gameObject, that gives the following code:

 TComponent FindClosest<TComponent>() where TComponent : $$anonymous$$onoBehaviour {
         TComponent[] allobjects=GameObject.FindObjectsOfType<TComponent>();
         float closestdis=$$anonymous$$athf.Infinity;
         TComponent closest=null;
         foreach (TComponent t_comp in allobjects) {
             float dis=(transform.position-t_comp.transform.position).magnitude;
             if(dis<closestdis && !(t_comp.gameObject==this.gameObject)) {
                 closestdis=dis;
                 closest=t_comp;
             }
         }
         return closest;
     }

Called using:

     Food closestfood=FindClosest<Food>();
avatar image
0

Answer by Tuncer · Jan 13, 2016 at 02:44 PM

Call :

 GameObject closestfood=FindClosest(typeof(Food));
Comment
Add comment · Show 1 · 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 Red Owl Games · Jan 13, 2016 at 10:11 PM 0
Share

I tried this by calling:

     GameObject closestfood2=FindClosest2 (typeof(Food));
 with FindClosest2:
     GameObject FindClosest2(Type t_component) {
             GameObject[] allobjects=(GameObject[])GameObject.FindObjectsOfType(t_component);
             float closestdis=$$anonymous$$athf.Infinity;
             GameObject closest=null;
             foreach (GameObject t_object in allobjects) {
                 float dis=(transform.position-t_object.transform.position).magnitude;
                 if(dis<closestdis && !(t_object.gameObject==this.gameObject)) {
                     closestdis=dis;
                     closest=t_object;
                 }
             }
             return closest;
         }

But this gives an error I don't quite understand. This may still be a valid solution but it requires some more research. Error: InvalidCastException: Cannot cast from source type to destination type. Code line:

 GameObject[] allobjects=(GameObject[])GameObject.FindObjectsOfType(t_component);

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

c# animation.Play("animation") 0 Answers

Adding classes to objects 0 Answers

Is there no way to inherit children's components for validation/checking purposes? 1 Answer

Children and parents in relative space 0 Answers

Adding created component to game object. 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