'New to programming and I cant seem to figure out how to disable a powerup in the game I am making
I am most likely going about this the wrong way so any help would be greatly appreciated.
The problem I am having is that when I pick up the power up my lasers turn to the correct shot but then don't switch back after a certain amount of time. Any idea how or why its not getting rid of my supershot buff?
private void Fire()
{
if (Input.GetButtonDown("Fire1"))
{
if (ActivateSuperShot)
{
StartCoroutine(DisableSuperShotPowerup());
superShotFiringCoroutine = StartCoroutine(SuperShotFireContinuously());
}
else
{
firingCoroutine = StartCoroutine(FireContinuously());
}
}
if (Input.GetButtonUp("Fire1"))
{
StopCoroutine(firingCoroutine);
StopCoroutine(superShotFiringCoroutine);
}
}
IEnumerator SuperShotFireContinuously()
{
while (true)
{
FireSuperShot();
}
}
IEnumerator FireContinuously()
{
while (true)
{
FireNormalLaser();
}
}
IEnumerator DisableSuperShotPowerup()
{
yield return new WaitForSeconds(powerupTime);
ActivateSuperShot = false;
}
//Activate PowerUp in seperate Script
if (player != null)
{
switch (powerupID)
{
//0= shield 1= speed 2=SuperShot
case 0:
player.ActivateShield();
break;
case 1:
player.ActivateSpeed();
break;
case 2:
player.ActivateSuperShot = true;
break;
default:
Debug.Log("Invalid Powerup");
break;
}
}
Thanks for your help!
Solution 1:[1]
Instead of beginning the coroutine that stops the powerup on input, have it begin when the powerup is activated:
bool activateSuperShot;
private void Fire()
{
if (Input.GetButtonDown("Fire1"))
{
if (activateSuperShot)
{
superShotFiringCoroutine = StartCoroutine(SuperShotFireContinuously());
}
else
{
firingCoroutine = StartCoroutine(FireContinuously());
}
}
if (Input.GetButtonUp("Fire1"))
{
StopCoroutine(firingCoroutine);
StopCoroutine(superShotFiringCoroutine);
}
}
IEnumerator SuperShotFireContinuously()
{
while (true)
{
FireSuperShot();
}
}
IEnumerator FireContinuously()
{
while (true)
{
FireNormalLaser();
}
}
IEnumerator DisableSuperShotPowerup()
{
yield return new WaitForSeconds(powerupTime);
activateSuperShot = false;
}
public void ActivateSuperShot()
{
activateSuperShot = true;
StartCoroutine(DisableSuperShotPowerup());
}
//Activate PowerUp in seperate Script
if (player != null)
{
switch (powerupID)
{
//0= shield 1= speed 2=SuperShot
case 0:
player.ActivateShield();
break;
case 1:
player.ActivateSpeed();
break;
case 2:
player.ActivateSuperShot();
break;
default:
Debug.Log("Invalid Powerup");
break;
}
}
note: in C# code, fields are typically camelCase.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ruzihm |
