Skip to content

Instantly share code, notes, and snippets.

@Curookie
Created December 18, 2017 10:23
Show Gist options
  • Save Curookie/c339ce36bc6c7601dc8883028605ad5b to your computer and use it in GitHub Desktop.
Save Curookie/c339ce36bc6c7601dc8883028605ad5b to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyCtrl : 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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment