I am currently working on a game where the Enemy follows the player and then shoots. Right now the shooting goes on forever. I tried to add a cooldown but it doesn't seem to be working. Do you know How I could improve/Change my gun cooldown to work?,I am making a game where the enemy finds the player and shoots the player. Currently it will not stop shooting until the player is dead. I tried to add a cooldown but it doesn't seem to be working.
(Below is the code for the game)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
int MoveSpeed = 4;
int MaxDist = 10;
int MinDist = 5;
public Transform Player;
public int damage = 10;
public float range = 100f;
public Transform FirePoint;
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
StartCoroutine(TimerRoutine());
}
}
}
private IEnumerator TimerRoutine()
{
RaycastHit hit;
if (Physics.Raycast(FirePoint.transform.position, FirePoint.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Health player = hit.transform.GetComponent();
if (player != null)
{
player.TakeDamage(damage);
yield return new WaitForSeconds(5);
}
}
}
}
↧