Change AI Follow Players

I am making a script that will make the AI follow the player. If the player is caught, it will follow the second player. If the second player is caught, it will chase the third player. And so on.

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {
	public Transform target;
	public int moveSpeed;
	public int rotationSpeed;
	public int maxDistance;
	
	private Transform myTransform;
	
	void Awake() {
		myTransform = transform;
	}
	
	// Use this for initialization
	void Start () {
		GameObject go = GameObject.FindGameObjectWithTag("Player");
		
		target = go.transform;
		
		maxDistance = 1;
	}
	
	// Update is called once per frame
	void Update () {
		Debug.DrawLine(target.position, myTransform.position, Color.yellow);
		
		//Look at target
		myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
		
		if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
		//Move towards target
		myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
		}
	}
}

That’s what I got so far.

var players = gameObject.FindGameObjectsWithTag(“PlayerNotCaught”);

	var distance = Mathf.Infinity; 
    var position = transform.position;
    // Iterate through them and find the closest one
    for (var go : GameObject in players)  {
    	
    	if (go != null)
    	{
        var diff = (go.transform.position - position);
        var curDistance = diff.sqrMagnitude; 
        if (curDistance < distance) {
        	
            target = go.transform;
            distance = curDistance;
        }
    	}
    }

Put that code in the Update() Function, and get rid target = go in Start(). Change the tags of your players according to if they’re caught or not. Not caught will have the tag “PlayerNotCaught” so the AI can determine them from the rest of the players.

This script will choose the closest not caught player, but if you want to go in order of player 1, 2, 3, 4, etc., you will have to use an if statement according to the current player in the array. Something like, if (player == 1) else if (player == 2) then target = player.