NullReferenceException - BurgZerg tutorial issue

Hey everyone,

I’m going through a tutorial done by BurgZerg and I’m having issues with the EnemyAttack.cs

I have tried searching other questions but I am unable to come to a logical conclusion. I am copying his script down to the last detail and I’m getting a scripting error.

The error I am getting is:
“NullReferenceException: Object reference not set to an instance of an object
EnemyAttack.Attack () (at Assets/Scripts/System/EnemyAttack.cs:39)
EnemyAttack.Update () (at Assets/Scripts/System/EnemyAttack.cs:24)”

The code for EnemyAttack.cs is

using UnityEngine;
using System.Collections;

public class EnemyAttack : MonoBehaviour 
{
    public GameObject target;
    public float attackTimer;
    public float coolDown;

    void Start ()
    {
        attackTimer = 0f;
        coolDown = 1f;
    }

    void Update()
    {
        if (attackTimer > 0)
            attackTimer -= Time.deltaTime;
        if (attackTimer < 0)
            attackTimer = 0;
        if (attackTimer == 0)
        {
            Attack();
            attackTimer = coolDown;
        }
    }

    private void Attack()
    {
        float distance = Vector3.Distance(target.transform.position, transform.position);
        Vector3 dir = (target.transform.position - transform.position).normalized;
        float direction = Vector3.Dot(dir, transform.forward);
        if(distance < 2.5f)
        {
            if(direction > 0)
            {
                PlayerHealth eh = (PlayerHealth)target.GetComponent("PlayerHealth");
                eh.AdjustCurrentHealth(-10);
            }
        }
    }
}

I don’t understand why I am getting these errors. I have assigned the target in the inspector and set all the variables.

Please help !!!

Looks like your ‘target’ gameobject does not have a PlayerHealth script component attached to it.

Of course !!!
Thank you !!!

I just realised that I have my scripts attached to empty objects on my players and enemies…don’t know why, seemed like a good idea at the time hahaha

Thanks HarshadK