- Home /
Timed Attack System
I am trying to make a timed attack system. it needs to start the timer when an enemy is acquired..but there is a bug..as soon as the next enemy is killed it quickly starts the timer and attacks twice in a short period of time...here is the code: (AttackWait is the timer that says canAttack is true after a "waitForSeconds" command), and enemyObject is the gameObject that tells the script which object to attack...Any ideas on how to solve this?
if(enemyObject == null)
{
canAttack = false;
canCheckEnemy = true;
}
if(enemyObject != null && canAttack == false && canCheckEnemy == true)
{
AttackWait();
canCheckEnemy = false;
}
//if there is an enemy...attack it
if(enemyObject != null && canAttack == true)
{
canAttack = false;
Attack();
}
Answer by ABerlemont · Jun 11, 2014 at 09:34 AM
If I understood your question correctly here is one way to delay attacks when you have a target :
using UnityEngine;
using System.Collections;
public class TimedAttack : MonoBehaviour {
GameObject enemyObject;
float attackTimer = 0f;
void Update () {
//don't do anything without target
if(enemyObject == null) return;
//found target, what now ?
if(attackTimer <= 0f) attackTimer = 1f; // wait 1 second before attacking
//wait for attack
if(attackTimer > 0f){
attackTimer -= Time.deltaTime;
if(attackTimer <= 0f){
attack();
}
}
}
void attack(){
attackTimer = 0f; // reset cooldown
}
}
Your solution looks like it works great! I fixed the problem myself by adding a variable:
function AttackWait() { checkCount += 1;
if(checkCount == 1)
{
yield WaitForSeconds(Random.Range(attackTimeInterval - attackTimeRandomRange, attackTimeInterval + attackTimeRandomRange));
canAttack = true;
}
}
So it only executes if its the first AttackWait(); command..then I reset it when it attacks.