- Home /
A way to run code during WaitForSeconds?
Hello everyone!
I currently have a character in my game that can attack by pressing a certain button. When that button is pressed, i also want him to dash in that direction for a bit, before i let the player control him again.
This is how i fix it right now:
if (Input.GetKeyDown(KeyCode.Z))
{
Attack();
StartCoroutine(Dash(moveX, moveY, dashSpeed, dashTime));
}
void Attack()
{
Collider2D[] hitenemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange,
enemyLayers);
foreach(Collider2D enemy in hitenemies)
{
Debug.Log("I hit " + enemy.name);
enemy.GetComponent<EnemyScript>().TakeDamage(attackDamage);
}
}
IEnumerator Dash(float moveX, float moveY, float dashSpeed, float seconds)
{
//canMove allows the player to move
GetComponent<PlayerMovement>().canMove = false;
//This makes the player dashes at the right direction
playerrb.velocity += new Vector2(moveX * dashSpeed, moveY * dashSpeed);
yield return new WaitForSeconds(seconds);
GetComponent<PlayerMovement>().canMove = true;
}
(I left out a bit of code that i did not think was necessary, but feel free to correct me in the comments)
However, the attack function is only called at the very beginning. Meaning that, when the player dashes, it does not registers if an enemy is in the "attack circle" and thus, does not attack it.
So, my problem is this. Is there a way to somehow run this Attack function during a waitforseconds? Or can i solve this problem in a better way?
Feel free to ask questions about the code or the game, if you need it
Thanks in advance!
make a bool that you set true just before the wait for seconds part and set it false immediately afterwards......then simply put a condition in the update method that while the bool is true.....you can dash
Answer by Namey5 · Jul 16, 2021 at 03:41 AM
What you can do is replace WaitForSeconds with a manual poll loop and call your attack function while that loop is running, i.e.
IEnumerator Dash(float moveX, float moveY, float dashSpeed, float seconds)
{
//canMove allows the player to move
GetComponent<PlayerMovement>().canMove = false;
//This makes the player dashes at the right direction
playerrb.velocity += new Vector2(moveX * dashSpeed, moveY * dashSpeed);
// Accumulate the amount of time that has passed per frame until we reach the desired time
for (float t = 0f; t < seconds; t += Time.deltaTime)
{
// Wait for the next frame
yield return null;
// Run the attack function now on the new frame
Attack ();
}
GetComponent<PlayerMovement>().canMove = true;
}
Hmm right, this is actually a more efficient method than $$anonymous$$e