Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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!
- GameObject currentTarget;
- List<GameObject> tanks;
- void Start()
- {
- tanks = new List<GameObject>(GameObject.FindGameObjectsWithTag("Tank"));
- tanks.Remove(this.gameObject);
- // Get closest tank
- GetClosestTank();
- }
- private void GetClosestTank()
- {
- int closestTankIndex = 0;
- float closestDst = float.MaxValue;
- Vector3 myPos = transform.position;
- for (int i = 0; i < tanks.Count; i++)
- {
- // Check if the tank we're looking at is closer than the closest tank
- float dstToTank = (myPos - tanks[i].transform.position).sqrMagnitude; // sqrMagnitude is faster than Vector3.Distance
- if (dstToTank < closestDst)
- {
- // If it is the closest then update values
- closestDst = dstToTank;
- closestTankIndex = i;
- }
- }
- // Finally set currentTarget to the closest tank!
- currentTarget = tanks[closestTankIndex];
- }
Advertisement
Add Comment
Please, Sign In to add comment