Search Unity

How to detect which game object in the scene is the fastest?

Discussion in 'Scripting' started by Alond, Apr 10, 2015.

  1. Alond

    Alond

    Joined:
    Dec 9, 2013
    Posts:
    12
    Hi guys.
    I'm working on a simple 2d game and I have a problem that I hope someone of you can help me with it.
    I have a lot of gameobjects in the scene that Instantiate and die all the time, each one of them gets a random speed value. I need to detect the fastest gameobject on the screen and give it a different color.
    I don't know how to do it and I checked many forums and could not find anything relevant...
    I'll appreciate any help... THANKS!
     
  2. Voxel-Busters

    Voxel-Busters

    Joined:
    Feb 25, 2015
    Posts:
    1,968
    I suppose you are maintaining a Pool system for this. (If not, I suggest to do that as you mentioned you are creating lot!)

    Just keep track the gameobject for which you are assigning current max speed value when ever you create a GameObject(or pick from pool) and make sure you update once it die as well.

    This way you will have the reference to the game object which is having high speed anytime.

    If your GO's can be offscreen after creation, You need to go for an advanced approach than above.
    Maintain alist of ACTIVE game objects (by tracking their spawn and death). Run in a forloop and assign the color for the one with highest speed. Here you need to check if the render isVisible flag is active or not.

    Even though there are other ways to do this, The above will get you started as a first step! Good luck!
     
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    You'll have to find a list of all of these objects; loop through all of them; grab their velocities; and mark which one is fastest. My guess is that the first step is where you're having trouble.

    There are a couple of ways to go about this. One is to use tags, and GameObject.FindAllGameObjectsWithTag. Another is to use a script that is attached to these objects, and use FindObjectsByType<YourScript>() (this would be my recommendation). There are other ways depending on how the scene is set up.

    Code (csharp):
    1.  
    2. YourScript[] allThings = FindObjectsOfType<YourScript>();
    3. float maxVelocity = 0f;
    4. YourScript fastestObject = null;
    5. for (int t=0;t<allThings.Length;t++) {
    6. Rigidbody thisRB = allThings[t].rigidbody;
    7. float thisRBVelocity = thisRB.velocity.magnitude;
    8. if (thisRBVelocity > maxVelocity) {
    9. maxVelocity = thisRBVelocity;
    10. fastestObject = allThings[t];
    11. }
    12. }
    13.  
    It'd be recommended (for performance) that you store the result of FindObjectsOfType, and only refresh that when the list of objects might change.
     
  4. Alond

    Alond

    Joined:
    Dec 9, 2013
    Posts:
    12
    WOW thank you so much!
    I'll try it out right away :))