- Home /
Finding enemies from a list script
Hey I have a building that I want to find the nearest enemy via another scrip I have where I store the enemy's how do I make the building get the enemy list and then find the nearest enemy
i have defined the enemy list enemiesManager = FindObjectOfType();
this is my targetfinder where the enemies should be from the enemies list
public void TargetFinder()
{
currentTargetDistance = Mathf.Infinity;
foreach (var x in enemies)
{
float distance = Vector3.Distance(transform.position, x.transform.position);
if (distance < currentTargetDistance)
{
myTarget = x;
displayText.text = "My target: " + x + "\n Distance to Target: " + distance; //skal fjernes nå det er helt klart
currentTargetDistance = distance;
}
}
}
this is the enemy list
public class EnemiesManager : MonoBehaviour
{
public List<GameObject> _allEnemies = new List<GameObject>();
public static EnemiesManager Current;
private void Awake()
{
if (Current == null)
Current = this;
}
}
Answer by austephner · Jan 31, 2020 at 04:00 PM
There's a bazillion different ways to do target finding, so you just have to settle on the one that makes the most sense for your project. One that I find easy for prototyping and spinning up new projects quickly is the singleton pattern - create a static reference out of EnemiesManager
such that any TargetFinder
can quickly and easily access the current list. You could even have a method inside of the manager class that takes a position and automatically finds the closest enemy to that position. Example:
public GameObject GetEnemyClosestToPoint(Vector3 point)
{
GameObject closestEnemy = null;
float closestEnemyDistance = 0.0f;
if (_allEnemies.Count > 0)
{
// by default grab first enemy
closestEnemy = _allEnemies[0];
closestEnemyDistance = Vector3.Distance(closestEnemy.transform.position, point);
}
foreach (var enemy in _allEnemies)
{
if (enemy == closestEnemy) continue;
var distance = Vector3.Distance(enemy.transform.position, point);
if (distance < closestEnemyDistance)
{
closestEnemy = enemy;
closestEnemyDistance = distance;
}
}
return closestEnemy;
}
looks like you're already using the singleton pattern, my mistake. But you're on the right path in my opinion!
I found out how to do it but thanks for your help :)
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Mario first person game, help? 1 Answer
Canduct and movement of an enemy 0 Answers
Make an enemy follow along a wall 2 Answers
Problem with adding items to a list 1 Answer