- Home /
C# - Coroutines for Abilities
Hi. I am currently trying to create an Ability system in unity using coroutines. I already have the controls set up to activate them, but coroutines always seem a bit tricky to use properly. Simply, each ability the player has will use a cooldown of a set amount and count down until 0. The ability will be unusable during the cooldown, and when the cooldown reaches 0 the ability can be used again, just like in many RPG and Action games.
One Ability for example (below) uses a coroutine to set the players max speed to a higher value, and then reset it after the cooldown reaches 0. However, the coroutine keeps repeating, as it is not stopped anywhere except after the cooldown, and the maxspeed is always increasing, instead of staying at the fixed number.
IEnumerator Dash(){
while (true) {
Debug.Log ("Dash used.");
float maxspeed = PlayerMaxSpeed *= 1.25f;
float minspeed = PlayerMaxSpeed;
PlayerMaxSpeed = maxspeed;
yield return new WaitForSeconds (//whatever the cooldown is, say 10 seconds);
PlayerMaxSpeed = minspeed;
yield return false;
}
}
Any help in this issue will be greatly appreciated.
not sure, wish i knew more about coroutines than i do, but i believe thats how you use a coroutine
You use a coroutine however you see fit. :-) They are blocks of code that will run asynchronously to do whatever you need them to do. Sometimes it makes sense to start a routine and have it run forever, but this doesn't seem to be one of those cases.
I'm confused by your setup. It looks like some player input will trigger this, but then it stays here forever due to the while loop. What is the while loop doing here?
Answer by dev-waqas · Jan 16, 2018 at 05:24 PM
The while loop is calling this co routine logic again every frame. Simply remove while loop and it will be all fine.
IEnumerator Dash(){
Debug.Log ("Dash used.");
float maxspeed = PlayerMaxSpeed *= 1.25f;
float minspeed = PlayerMaxSpeed;
PlayerMaxSpeed = maxspeed;
yield return new WaitForSeconds (//whatever the cooldown is, say 10 seconds);
PlayerMaxSpeed = minspeed;
yield return null;
}
Thank you. This worked for the most part. However, every time the Ability is used the coroutine activates, and no cooldown is triggered. How would I go about doing this?
There isn't anything here that would prevent another one from being activated. You might want to have some flag within the coroutine to handle the cooldown -- is false while the coroutine is running, and then is true once it finishes.
Your answer
Follow this Question
Related Questions
Had difficulties implementing intro to Coroutines from unitypatterns.com. Help? 1 Answer
Generic Cooldown IEnumerator? 1 Answer
Can't get while loop to execute more than once in a coroutine before yielding [Solved] 2 Answers
Toggling bools automatically using coroutines 1 Answer
Multiple Cars not working 1 Answer