StopCoroutine() Not Working
Other solutions previously posted do not make it work either.
Saving the coroutine in a variable does nothing.
It prints "stopped" on the console, so the statement does return true when the mouse is released.
void Update() {
StartAndStopFiring();
}
void StartAndStopFiring()
{
// If LMB pressed
if(Input.GetMouseButtonDown(0))
{
//Start shooting
StartCoroutine(FireWeapon());
}
// If LMB released
else if(Input.GetMouseButtonUp(0))
{
//Stop shooting
StopCoroutine(FireWeapon());
print("stopped");
}
}
IEnumerator FireWeapon()
{
while(true)
{
Quaternion quaternion;
if (isFacingRight)
{
// Bullet moves right
quaternion = Quaternion.identity;
}
else
{
// Bullet moves left
quaternion = Quaternion.Euler(0, 180, 0);
}
// Instantiates the bullet at the spawn point with the quaternion set earlier and the parent as the organizer
Instantiate(bullet, bulletSpawn.position, quaternion, bulletParent);
// For example, if the firingRate is 20, it waits 0.05 seconds
yield return new WaitForSeconds(1 / firingRate);
}
}
Answer by Hellium · Jan 28, 2019 at 09:11 AM
When calling StooCoroutine
, you must have a reference to the started coroutine:
private IEnumerator fireCoroutine;
void StartAndStopFiring()
{
// If LMB pressed
if(Input.GetMouseButtonDown(0))
{
//Start shooting
fireCoroutine = FireWeapon();
StartCoroutine(fireCoroutine);
}
// If LMB released
else if(Input.GetMouseButtonUp(0))
{
//Stop shooting
StopCoroutine(fireCoroutine);
}
}
It does work. I've just tried it, and the coroutine stops running when the left mouse button is released.
Uh, I guess the same exact code that didn't work 12 hours ago and 23 $$anonymous$$utes ago works now. It's working flawlessly now for some reason. Thanks for the help.
Answer by tormentoarmagedoom · Jan 28, 2019 at 08:44 AM
Good day.
First, Why you encapsule all FireWeapon in a while (true) ?? its the same as nothing...
Anyway. You are using GetMouseButtonDown wich only is executed the 1st frame the button is clicked. And, as i dont see the method calls itself again, it will only be executed once if you hold the button.
As the FireWeapon() is only executed once, when it reached the end, it does not need to be "stopped"
I recommend you to just call itself again right after the yield command
[...]
// For example, if the firingRate is 20, it waits 0.05 seconds
yield return new WaitForSeconds(1 / firingRate);
StartCoroutine(FireWeapon());
And remove that while (true) that makes nothing!
Good luck!
Bye!
Actually, while(true) is doing something, it's there so the coroutine would repeat until it is told to stop. FireWeapon() is not executed once, it is executed until an external command tells it to stop (which is not working).
Your confusion might be from me not putting the Update() function, my bad.
Calling a function inside itself is not the best idea.
But I'll update the code so that it's clear.