Guest User

Untitled

a guest
Aug 16th, 2021
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.01 KB | None | 0 0
  1. // Assuming there are no more tanks that spawn during gameplay you can store them so you don't have to call FindGameObjectsWithTag all the time as it's a slow operation!
  2.  
  3. GameObject currentTarget;
  4. List<GameObject> tanks;
  5.  
  6. void Start()
  7. {
  8.     tanks = new List<GameObject>(GameObject.FindGameObjectsWithTag("Tank"));
  9.     tanks.Remove(this.gameObject);
  10.  
  11.     // Get closest tank
  12.     GetClosestTank();
  13. }
  14.  
  15. private void GetClosestTank()
  16. {
  17.     int closestTankIndex = 0;
  18.     float closestDst = float.MaxValue;
  19.    
  20.     Vector3 myPos = transform.position;
  21.     for (int i = 0; i < tanks.Count; i++)
  22.     {
  23.         // Check if the tank we're looking at is closer than the closest tank
  24.         float dstToTank = (myPos - tanks[i].transform.position).sqrMagnitude; // sqrMagnitude is faster than Vector3.Distance
  25.         if (dstToTank < closestDst)
  26.         {
  27.             // If it is the closest then update values
  28.             closestDst = dstToTank;
  29.             closestTankIndex = i;
  30.         }
  31.     }
  32.    
  33.     // Finally set currentTarget to the closest tank!
  34.     currentTarget = tanks[closestTankIndex];
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment