Hello I followed a video tutorial that works with navmesh But the game doesn’t end when the player reaches 0 health
The video is called Enemies Made Easy (Unity3D + NavMesh) by Developer Jake
Here is the enemy code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Enemy : MonoBehaviour
{
[Range(0,50)] [SerializeField] float attackRange = 5, sightRange = 20 , timeBetweenAttacks = 3;
[Range(0, 20)][SerializeField] int power; // The amount of damge that the enemy does
private NavMeshAgent thisEnemy;
public Transform playerPos;
private bool isAttacking; // If the enemy is currently attacking
private void Start()
{
thisEnemy = GetComponent<NavMeshAgent>();
playerPos = FindObjectOfType<PlayerHealth>().transform;
}
private void Update()
{
float distanceFromPlayer = Vector3.Distance(playerPos.position, this.transform.position); //The distance between the Player and the Enemy
if (distanceFromPlayer <= sightRange && distanceFromPlayer > attackRange && !PlayerHealth.isDead)
{
isAttacking = false;
thisEnemy.isStopped = false;
StopAllCoroutines();
ChasePlayer();
}
if (distanceFromPlayer <= attackRange && !isAttacking && !PlayerHealth.isDead)
{
thisEnemy.isStopped = true; // Stop the Enemy from moving
StartCoroutine(AttackPlayer());// Start attacking the player
}
if (PlayerHealth.isDead)
{
thisEnemy.isStopped = true;
}
}
private void ChasePlayer()
{
thisEnemy.SetDestination(playerPos.position); // Set the enemy's destination to the player.
}
private IEnumerator AttackPlayer()
{
isAttacking = true;
yield return new WaitForSeconds(timeBetweenAttacks); // Wait for the time between attacks
FindObjectOfType<PlayerHealth>().TakeDamge(power); // Damage the player with 'power' damge.
isAttacking = false;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.cyan;
Gizmos.DrawWireSphere(this.transform.position, sightRange);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(this.transform.position, attackRange);
}
}
Here is the Player Health
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
[Range(0, 200)] public int startHealth = 100, currentHealth;
public static bool isDead;
private void Start()
{
currentHealth = startHealth; // Set the current health to be the start health, when the game starts.
}
private void Update()
{
if (currentHealth <= 0 && !isDead)
{
isDead = true;
Debug.Log("The Player has died!");
}
}
public void TakeDamge(int amount)
{
currentHealth -= amount;
}
}