Ai Script Help

I need help with my Ai. I need a script that will locate the nearest object with the tag player and then follow it. I have a multiplayer game any my old ai script (which I deleted) only picked one of the objects.

Covered in the script reference: http://unity3d.com/support/documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html

// Print the name of the closest Player
print(FindClosestPlayer().name);

// Find the name of the closest Player
function FindClosestPlayer () : GameObject {
// Find all game objects with tag Player
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Player");
var closest : GameObject;
var distance = Mathf.Infinity;
var position = transform.position;
// Iterate through them and find the closest one
for (var go : GameObject in gos) {
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}

Hope this helps!

It has helped alot but I don’t know how to get the ai to follow the chosen player

//...
closest = go;
distance = curDistance;
}
}
return closest;
//add something like:
var lookToPlayer  = Quaternion.LookRotation(closest.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, lookToPlayer, Time.deltaTime /smooth);

//and in the fixed update:
var movement:Vector3 = Vector3.forward * speed; // just move along z axis...
	transform.Translate(movement);

Whoops, knew I’d leave something out. Thanks AnyKey.

how do I put that together? I get lots of errors when I put both of those together.

this is not testet, but it should work:

var smooth : float = 2.0;
var speed: float = 1.5:
function Update(){
	FindClosestPlayer();
}
// Print the name of the closest Player
//print(FindClosestPlayer().name);

// Find the name of the closest Player
function FindClosestPlayer(){
	// Find all game objects with tag Player
	var gos : GameObject[];
	gos = GameObject.FindGameObjectsWithTag("Player");
	var closest : GameObject;
	var distance = Mathf.Infinity;
	var position = transform.position;
	// Iterate through them and find the closest one
	for (var go : GameObject in gos) {
		var diff = (go.transform.position - position);
		var curDistance = diff.sqrMagnitude;
		if (curDistance < distance) {
			closest = go;
			distance = curDistance;
		}
	}
	return closest;
	//add something like:
	if (curDistance <= 100){
		var lookToPlayer  = Quaternion.LookRotation(closest.transform.position - transform.position);
		transform.rotation = Quaternion.Slerp(transform.rotation, lookToPlayer, Time.deltaTime /smooth);
	}
}

function FixedUpdate(){
	var movement:Vector3 = Vector3.forward * speed; // just move along z axis...
	transform.Translate(movement);
}

The enemies on my game only fly off in a random direction

just copy´n paste doesn´t work in 99,99999999999999999999999999999999% :wink: