I’m having a problem with the Survival Shooter Tutorial, I’m on stage 4 where you set up the first enemy. The problem is the enemy wont follow my player. At the bottom of the screen this error comes up: NullReferenceException: Object reference not set to an instance of an object CompleteProject.EnemyMovement.Update () (at Assets/_CompletedAssets/Scripts/Enemy/EnemyMovement.cs:27)
I think that its a problem with the script, any help is appreciated. The script is typed as:
using UnityEngine;
using System.Collections;
namespace CompleteProject
{
public class EnemyMovement : MonoBehaviour
{
Transform player; // Reference to the player’s position.
PlayerHealth playerHealth; // Reference to the player’s health.
EnemyHealth enemyHealth; // Reference to this enemy’s health.
NavMeshAgent nav; // Reference to the nav mesh agent.
void Awake ()
{
// Set up the references.
player = GameObject.FindGameObjectWithTag (“Player”).transform;
playerHealth = player.GetComponent ();
enemyHealth = GetComponent ();
nav = GetComponent ();
}
void Update ()
{
// If the enemy and the player have health left…
if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
{
// … set the destination of the nav mesh agent to the player.
nav.SetDestination (player.position);
}
// Otherwise…
else
{
// … disable the nav mesh agent.
nav.enabled = false;
}
}
}
}
using UnityEngine;
using System.Collections;
namespace CompleteProject
{
public class EnemyMovement : MonoBehaviour
{
Transform player; // Reference to the player's position.
PlayerHealth playerHealth; // Reference to the player's health.
EnemyHealth enemyHealth; // Reference to this enemy's health.
NavMeshAgent nav; // Reference to the nav mesh agent.
void Awake ()
{
// Set up the references.
player = GameObject.FindGameObjectWithTag ("Player").transform;
playerHealth = player.GetComponent <PlayerHealth> ();
enemyHealth = GetComponent <EnemyHealth> ();
nav = GetComponent <NavMeshAgent> ();
}
void Update ()
{
// If the enemy and the player have health left...
if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
{
// ... set the destination of the nav mesh agent to the player.
nav.SetDestination (player.position);
}
// Otherwise...
else
{
// ... disable the nav mesh agent.
nav.enabled = false;
}
}
}
}
You need to do some null-checking. Print or Debug.Log whether or not playerHealth is null after the player.GetComponent(), or enemyHealth is null after the GetComponent(). One of them doesn’t actually have the component attached, so when you go to check for .currentHealth, you’re trying to get a member of “NULL”, which is impossible.