I am working on an assignment for a course and I need to make the enemy deal damage to the player after 5 seconds of touching or being near the player.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyController : MonoBehaviour {
public float LookRadius = 10f;
public float DamageRadius = 0.5f;
public float Time = 0f;
Transform target;
NavMeshAgent agent;
// Use this for initialization
void Start () {
target = PlayerManager.instance.player.transform;
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update () {
float distance = Vector3.Distance(target.position, transform.position);
if (distance <= LookRadius)
{
agent.SetDestination(target.position);
}
if (distance <= DamageRadius)
{
}
}
}
I have all of this so far, I just don’t know what to put in the last “if” statement to get it to work.
public float LookRadius = 10f;
public float DamageRadius = 0.5f;
public float damageDelay = 5f;
private float damageTimer = 0f;
Transform target;
NavMeshAgent agent;
// Use this for initialization
void Start () {
target = PlayerManager.instance.player.transform;
agent = GetComponent();
}
// Update is called once per frame
void Update () {
float distance = Vector3.Distance(target.position, transform.position);
if (distance <= LookRadius)
{
agent.SetDestination(target.position);
}
if (distance <= DamageRadius)
{
damageTimer += Time.deltaTime;
if( damageTimer > damageDelay )
{
damageTimer -= damageDelay;
// Apply damage
// Change according to your scripts
Player player = target.GetComponent<Player>();
if( player != null )
player.ApplyDamage();
}
}
else
{
damageTimer = 0;
}
}
You can do this easily using Coroutines:
public float delay;
public bool immune = false;
public Update () {
if (CheckHit())
StartCoroutine(DamagePlayer(delay));
}
public bool CheckHit () {
if (immune)
return false;
// Do your own check here
return true;
}
IEnumerator DamagePlayer (float time) {
// Make the player Immune so it doesn't trigger multiple times
immune = true;
// Wait the amount of time
yield return new WaitForSeconds(time);
DealDamage ();
}
void DealDamage () {
Player player = target.GetComponent<Player>();
if( player != null )
player.ApplyDamage();
immune = false;
}