Hello, my friends. I hope someone can help me with this specific script I have. I’m working on programming a strategy game, and now I’m facing an issue with one of the scripts. It consumes high resources and creates a frame drop for me. The issue is that when the player searches for an object within the range, it executes the condition.
Please note that the translation is provided as is and may not perfectly reflect the intended meaning.
And now I’m going to write for you the line of code that is consuming high resources for me. I hope you can find a solution for me. I have great respect, appreciation, and love for you.
private void Update()
{
Collider enemies = Physics.OverlapSphere(transform.position, detectionRange,
LayerMask.GetMask(enemyTag));
GameObject nearestEnemy = GetNearestEnemy(enemies);
}
private GameObject GetNearestEnemy(Collider enemies)
{
GameObject nearestEnemy = null;
float nearestDistance = Mathf.Infinity;
foreach (Collider enemy in enemies)
{
float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
if (distanceToEnemy < nearestDistance)
{
nearestDistance = distanceToEnemy;
nearestEnemy = enemy.gameObject;
Target = nearestEnemy;
}
}
return nearestEnemy;
}