Does anyone know what causes this, the script now just throws this error?
NullReferenceException: Object reference not set to an instance of an object
EnemyController.Update () (at Assets/Scripts/EnemyScripts/EnemyController.cs:21)
public class EnemyController : MonoBehaviour {
public float lookRadius = 10f;
Transform target;
NavMeshAgent agent;
public Animator anim;
public float velocity;
private void Start()
{
target = PlayerManager.instance.player.transform;
agent = GetComponent();
}
private void Update()
{
velocity = agent.velocity.magnitude;
float distance = Vector3.Distance(target.position, transform.position);
if(distance <= lookRadius)
{
agent.SetDestination(target.position);
if (distance <= agent.stoppingDistance)
{
//Attack player
AttackPlayer();
FaceTarget();
}
else
{
StopAttackPlayer();
}
}
if(velocity > .1)
{
anim.SetFloat("speed", 1f);
}
else
{
anim.SetFloat("speed", 0f);
}
}
void FaceTarget()
{
Vector3 direction = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
}
void AttackPlayer()
{
anim.SetBool("attack", true);
}
void StopAttackPlayer()
{
anim.SetBool("attack", false);
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, lookRadius);
}
public void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
Die();
}
}
public void Die()
{
anim.SetBool("isDead", true);
agent.enabled = false;
Destroy(gameObject, 3f);
}
}
↧