- Home /
How to reset powerups effects and timer in unity ?
Hi everyone , may i ask ? How to reset powerups effect and timer when collect another powerups while the last one effects still running. Example : The invisible effects will last 8 seconds and in the interval of 8 seconds we collect another powerups and in this situation need to reset the timer and the coroutines.
This is my code. In this code , my timer not reset successfully and the effects of invisible too. Sorry for bad english.
```c using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class PowerUps : MonoBehaviour { private GameObject player; private GameObject powerUps; private float timeRemaining; private float maxTime=8.0f; public int count; private bool timer=false; private bool reset;
void Awake()
{
player=GameObject.FindGameObjectWithTag("Player");
powerUps=GameObject.FindGameObjectWithTag("Img");
}
void Start()
{
powerUps.SetActive(false);
timeRemaining=maxTime;
}
void Update()
{
count=FindObjectOfType<PlayerController>().InvisPowerUpsCount;
if(timer)
{
TimerOn();
}
else if(!timer)
{
powerUps.SetActive(false);
}
}
private void OnTriggerEnter(Collider Other)
{
if(Other.gameObject.tag=="Player")
{
GetComponent<MeshRenderer>().enabled=false;
GetComponent<SphereCollider>().enabled=false;
StartCoroutine(InvisiblePowerUp());
if(count>1)
{
reset=true;
StopCoroutine(InvisiblePowerUp());
StartCoroutine(InvisiblePowerUp());
}
}
}
void TimerOn()
{
if(reset==true)
{
timeRemaining=maxTime;
powerUps.GetComponent<Image>().fillAmount=1;
reset=false;
}
if(reset==false)
{
if(timeRemaining>0)
{
powerUps.SetActive(true);
timeRemaining-=Time.deltaTime;
powerUps.GetComponent<Image>().fillAmount=timeRemaining/maxTime;
}
else
{
timer=false;
}
}
}
IEnumerator InvisiblePowerUp()
{
timer=true;
player.GetComponent<Death>().isTrigger=false;
yield return new WaitForSeconds(8.0f);
timer=false;
player.GetComponent<Death>().isTrigger=true;
player.GetComponent<PlayerController>().InvisPowerUpsCount=0;
Destroy(gameObject);
}
} ```