Question by
Misterquick · Apr 11, 2016 at 07:36 AM ·
enemy ai
How to make enemy follow/find a certain object that is not the player?
Hi everyone I am new to unity and I'm trying my best to learn how to be a game programmer. I basically followed the Survival shooter game tutorial, but now I want to add some twist to the game. I want to make the enemy to be able to find my base and destroy it. This is my code so far:
using UnityEngine;
using System.Collections;
namespace CompleteProject
{
public class EnemyMovementBase : MonoBehaviour
{
Transform Base; // Reference to the base's position.
BaseHealth baseHealth; // Reference to the base's health.
EnemyHealth enemyHealth; // Reference to this enemy's health.
NavMeshAgent nav; // Reference to the nav mesh agent.
void Awake()
{
// Set up the references.
Base = GameObject.FindGameObjectWithTag("Base").transform;
baseHealth = Base.GetComponent<BaseHealth>();
enemyHealth = GetComponent<EnemyHealth>();
nav = GetComponent<NavMeshAgent>();
}
void Update()
{
// If the enemy and the base have health left...
if (enemyHealth.currentHealth > 0 && baseHealth.currentHealth > 0)
{
// ... set the destination of the nav mesh agent to the base.
nav.SetDestination(Base.position);
}
// Otherwise...
else
{
// ... disable the nav mesh agent.
nav.enabled = false;
}
}
}
}
It's basically the survival shooter enemy follow player script, but I change all the "player" to "base". I also tag my game object "base" but it is still not working. I'm getting the error: NullReferenceException: Object reference not set to an instance of an object; line 27. Thank you so much for your time.
Comment