im trying to make abilities to my open world fanasty game but i cant seem to find a working way to find the closest enemy
Start with tutorials for this ultra-basic ultra common thing in gamedev.
Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.
Two steps to tutorials and / or example code:
- do them perfectly, to the letter (zero typos, including punctuation and capitalization)
- stop and understand each step to understand what is going on.
If you go past anything that you don’t understand, then you’re just mimicking what you saw without actually learning, essentially wasting your own time. It’s only two steps. Don’t skip either step.
Imphenzia: How Did I Learn To Make Games:
Given that the enemies have all have the same script attached (called in ‘Enemy’ in this example) you can iterate through all the transforms and the distances to the player.
Enemy[] enemies = FindObjectsOfType<Enemy>();
Enemy closestEnemy;
float closestDistance;
foreach (Enemy enemy in enemies)
{
float distance = Vector3.Distance(enemy.transform.position, player.transform.position);
if (distance < closestDistance)
{
closestEnemy = enemy;
closestDistance = distance;
}
}
Be warned. All this code is off the top of my head. I might have messed up the syntax slightly and also it might not be the most efficient way. It’s kind of hard to tell what the best method would be without looking at your project.