#Short code review!
1 messages · Page 1 of 1 (latest)
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
this is a BIG no-no . . .
so I heard, but I can't think of any other way to work around it
I also realized how stupidly repetitive my code is like right now and got rid of one method
public class EnemyController : MonoBehaviour
{
[SerializeField] float attackRange = 5f;
private void Update()
{
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
float currentPlayer = GetClosestPlayer(players);
if (currentPlayer < attackRange)
{
print("Can attack");
}
}
private float GetClosestPlayer(GameObject[] players)
{
Transform nearestPlayer = null;
float minDist = Mathf.Infinity;
foreach (GameObject player in players)
{
float distance = Vector3.Distance(player.transform.position, transform.position);
if (distance < minDist)
{
nearestPlayer = player.transform;
minDist = distance;
}
}
return minDist;
}
}
you don't need to grab all players every frame. when a player is created, add them to a list. when they are destroyed, remove them from the list, then use the list to check the players . . .
Generally, if performance is a concern, you should use the profiler.
I'll look into the profiler, can you elaborate on this
nothing to elaborate, it's as i said. add each player to a list when they're created/added to the game. remove them from the list when they are destroyed. use the list to check for the closest player . . .