Find and follow nearest object

I’m making a game and in my game there are players and there are enemies and I want the enemies to attack the nearest player in range.

Well, what have you tried?

I’ve tried this but it’s only focusing on 1 object and it’s not good enough.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAI : MonoBehaviour
{
    public Transform target;
    public float within_range;
    public float speed;
    public float min_range;
    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target);
        var distance = Vector3.Distance(target.position, transform.position);
        if (distance <= within_range)
        {
            if (distance >= min_range)
            {
                transform.position += transform.forward * speed * Time.deltaTime;
            }
        }
    }
}
  1. You need to get a list of all players.

Search by tag? search by overlap sphere? find by script? have a script that stores all active instances of itself in a easily accessible place like a static collection? There’s like a bajillion ways… you just need to get a ref to all of them.

  1. Loop over that collection and do a distance comparison, keeping the smallest one.

  2. Replace ‘target’ in your EnemyAI with this player’s transform.

1 Like