- Home /
Why doesnt this bool take effect even though it does change?
Hello, i have been writing some code to make an attack with a cooldown and specific duration, this is the code
if (Input.GetKeyDown(KeyCode.E) && ableToAttack)
{
ableToAttack = false;
StartCoroutine(attackDuration(2));
StartCoroutine(attackCD(5));
toggleAttack = !toggleAttack;
attack.SetActive(toggleAttack);
attackParticles.SetActive(toggleAttack);
burning = toggleAttack;
burningSound.Play();
if (toggleAttack == false)
{
burningSound.Stop();
}
}
The code works as intended, the bool toggleAttack changes from false(its set value) to true when pressing E and it also turns to false when the 2 seconds the attackDuration corountine has get to 0, but the gameobjects attack and attackParticles dont change to false, they remain in the scene when they should have been turned off, any idea as to why this is happening? Any help would be appreciated
private IEnumerator attackCD(float waitTime)
{
yield return new WaitForSeconds(waitTime);
ableToAttack = true;
}
private IEnumerator attackDuration(float waitTime)
{
yield return new WaitForSeconds(waitTime);
toggleAttack = false;
}
Answer by tyruji · Jul 23, 2021 at 06:06 PM
You are not calling SetActive(false) on your gameobjects after these 2 seconds pass, so I suggest you call it in your "attackDuration" method, just after setting "toggleAttack".
but SetActive is set to toggleAttack, which would be false after the 2 seconds pass, wouldnt that have to work? Also how would i go about calling it in "attackDuration"?
No, it won't work - you are just setting the bool value of "toggleAttack", you are not updating the active state of any game object, here is how your coroutine should look like:
private IEnumerator attackDuration( float waitTime )
{
yield return new WaitForSeconds( waitTime );
toggleAttack = false;
attack.SetActive( false );
attackParticles.SetActive( false );
}
just tried it and it works perfectly, thank you very much