I am writing a script where the Enemy and Player distance is measured and Enemy attacks whenever it close to player. I have added my Hero object in the Serialized Field as well but it still throws error
NullReferenceException: Object reference not set to an instance of an object
EnemyAttack.Update () (at Assets/Scripts/EnemyAttack.cs:28)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAttack : MonoBehaviour
{
[SerializeField] private float range = 3f;
[SerializeField] private float timeBetweenAttacks = 1f;
private Animator anim;
private GameObject player;
private bool playerInRange;
private BoxCollider[] weaponColliders;
private EnemyHealth enemyHealth;
// Start is called before the first frame update
void Start()
{
weaponColliders = GetComponentInChildren <BoxCollider[]> ();
player = GameManager.instance.Player;
anim = GetComponent <Animator> ();
enemyHealth = GetComponent <EnemyHealth> ();
StartCoroutine (attack());
}
// Update is called once per frame
void Update()
{
if(Vector3.Distance(transform.position, GameManager.instance.Player.transform.position) < range && enemyHealth.IsAlive)
{
playerInRange = true;
}else{
playerInRange = false;
}
}
public IEnumerator attack()
{
Debug.Log("Hello");
if(playerInRange && !GameManager.instance.GameOver)
{
anim.Play("Attack");
yield return new WaitForSeconds(timeBetweenAttacks);
}
yield return null;
StartCoroutine(attack());
}
public void EnemyBeginAttack(){
foreach(var weapon in weaponColliders){
weapon.enabled = true;
}
}
public void EnemyEndAttack(){
foreach(var weapon in weaponColliders){
weapon.enabled = false;
}
}
}