- Home /
Script not working, help please
So this is kinda the continuation of this thread: http://answers.unity3d.com/questions/495573/use-of-unassigned-variable-script-from-script-refe.html which I already got help and the error disappeared but the script doesn't works so I've decided to make a new thread for it, this is my script: using UnityEngine; using System.Collections;
public class EnemyScript : MonoBehaviour {
public float health = 100;
public float speed = 100;
public GameObject[] gos;
public GameObject closestPlayer = null;
public float distance;
void FixedUpdate(){
transform.LookAt(closestPlayer.transform.position);
FindClosestEnemy();
}
GameObject FindClosestEnemy() {
gos = GameObject.FindGameObjectsWithTag("Player");
distance = Mathf.Infinity;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - transform.position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closestPlayer = go;
distance = curDistance;
}
}
return closestPlayer;
}
}
The script isn't finding the closest Player, so I'm getting this error: UnassignedReferenceException: The variable closestPlayer of 'EnemyScript' has not been assigned. You probably need to assign the closestPlayer variable of the EnemyScript script in the inspector. EnemyScript.FixedUpdate () (at Assets/Scripts/EnemyScript.cs:14)
Help me please, and thanks in advance
Answer by PAEvenson · Jul 18, 2013 at 04:18 PM
well now you need an if check to see if your closest enemy is null or not...
void FixedUpdate(){
if(closestPlayer != null)
{
transform.LookAt(closestPlayer.transform.position);
}
FindClosestEnemy();
}