I "borrowed" some code from the unity documentation trying to get an enemy to follow the closest player. My problem is that the closest Game Object variable is defined like this: `public void Example()
{
GameObject closest;
}
`
how do I get that variable to make the enemy move towards the closest player?
full code:
using UnityEngine;
using System.Collections;
public class FindClosest : MonoBehaviour
{
public float speed = 7f;
public GameObject FindClosestPlayer()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Player");
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
return closest;
}
public void Update()
{
transform.position = Vector3.MoveTowards(transform.position, go.transform.position, speed);
}
}
↧