How do I make an enemy only damage once per second?
void OnCollisionEnter2D(Collision2D col) { if (col.gameObject.name == "KP") { StartCoroutine(DamagePlayer()); DamagePlayer(); StartCoroutine(DamagePlayer()); }
}
public IEnumerator DamagePlayer() { //waits but doesnt force code to stop, make it do that yield return new WaitForSeconds(1); GameObject.Find("KP").GetComponent().DamagePlayer(damage); print("Waited"); }
My wait function does work in that it halts any damage being done to after one second, but all of the damage floods in after that one second. What I need is for the enemy to only deal damage once per every second and time the player hits the enemy, not constant damage while the player is touching the enemy.
Answer by seth_slax · Mar 21, 2016 at 11:39 PM
Please use the code formatting option to enter code, otherwise it's really hard to read it properly.
A solution off the top of my head would be to add a timer variable to the enemy script, like so:
float damTimer;
void Update(){
if(damTimer > 0){
damTimer -= Time.deltaTime;
}
}
OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.name == "KP") {
if(damTimer <= 0){
DamagePlayer();
}
}
}
public void DamagePlayer() {
damTimer = 1;
GameObject.Find("KP").GetComponent().DamagePlayer(damage);
}
@seth_slax Sorry, first post, but I will try it and see. Thanks.
@seth_slax Okay, only one problem now. The wait function works but only once. The damage is only being sent once and never again. It seems to have fixed one problem but created another, probably an easy fix though if I knew what I was doing.
Hmm, I'm not sure why that's happening. $$anonymous$$aybe try making the timer a public variable so you can see it in the inspector and make sure it's counting back down.
@seth_slax It is not counting back down, once it collides with the player, it stays at one and never goes back down.
Your answer
![](https://koobas.hobune.stream/wayback/20220612072809im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
[C#] Coroutine just won't stop! 2 Answers
"Can't add script behaviour AICharacterControl. The script needs to derive from MonoBehaviour!" ? 0 Answers
What is Coroutine, Yiel and IENumerator? 1 Answer
Instantiate object through a coroutine problem 1 Answer
"Can't add script behaviour AICharacterControl. The script needs to derive from MonoBehaviour!" ? 2 Answers