Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[SOLVED]FindObjectsOfType does not take into account base classes

Discussion in 'Scripting' started by Jymmy097, Aug 4, 2015.

  1. Jymmy097

    Jymmy097

    Joined:
    Jul 7, 2014
    Posts:
    67
    Hi everybody,
    I have this code:
    Code (CSharp):
    1. public class Tank:MonoBehaviour{•••}
    2.  
    3. public class TankAI:Tank{•••}
    4.  
    5. public static class AllTanks{
    6. public static Tank[] tanks(){
    7. return GameObject.FindObjectsOfType<Tank>();
    8. }
    9. }
    In my scene I have 2 TankAI, but the Array returned by tanks() does not contain them. I wish to avoid using FindObjectsWithTag. What is the problem with the above code?

    Thanks in advance.

    Jymmy097
     
    Last edited: Aug 5, 2015
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Tank isn't a GameObject, it's a component (a script) of type "Tank". Your return needs to be "return Tank[] FindObjectsOfType<Tank>();" and it'll return all of the tank components in the scene, which should include all derived components as well.

    Also, you should avoid the FindObjectsOfType() function, because it's exceedingly slow. If you have a parent object of all of the tank objects, then GetComponentsInChildren() on that parent would be far faster, or keeping an array of all tank objects in a parent that's automatically updated as the game progresses either by the children self-assigning themselves to the array or by the parent assigning them as it constructs the children, or something.
     
    Jymmy097 likes this.
  3. Jymmy097

    Jymmy097

    Joined:
    Jul 7, 2014
    Posts:
    67
    Thanks for your reply.

    I've found also the option to find those GameObjects with their tag by using FindObjectsWithTag.
    Anyway, the idea to use a parent gameobject for all tanks is good. I think I'll use it. Thanks a lot.

    Jymmy097