MLAPI - Zombie Follow To Closest Connected Player

Hello All,

This is a two part question with a little bit of background.

Currently working on my second project using MLAPI. I have 4 spawned players into a map and have a working 3 different zombies that will follow the player based off finding the tag “Player” when they spawn. However, currently it seems like they are only following the first player that is spawned in. (I’m assuming this is because they are either higher on the Hierarchy or because they are the server?) So two questions:

  1. Is there a way to get a list of users using MLAPI? I cannot seem to find anything in the documentation on this.

  2. Is there a way to have the AI choose a random player with the tag “Player” instead of just the first one on the hierarchy?

Below is my simple follow script.

public class BasicZombieFollow : MonoBehaviour
{
    public NavMeshAgent enemy;
    public Transform player;
    
    // Start is called before the first frame update
    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }

    // Update is called once per frame
    void Update()
    {
        enemy.SetDestination(player.position);
    }
}

You can use the namespace System.Linq, which provides great functions for modifying collections and sorting them easily. Here’s a way that you can detect if any objects are in the zombie’s range, only get objects tagged as enemy, and follow the closest enemy.

public class Follow : MonoBehaviour
{
    public NavMeshAgent enemy;
    public float Range;

    void Update()
    {
        var players = Physics.OverlapSphere(transform.position, Range)
            .Where(x => x.CompareTag("Player")).ToList();

        if (players.Count == 0)
            return;

        var sortedPlayers = players.OrderBy
            (x => Vector3.Distance(transform.position, x.transform.position));

        var closestPlayer = sortedPlayers.First();

        // Follow player
        enemy.SetDestination(closestPlayer.transform.position);
    }
}

@RobertGrospitch