in my c# code below I have a timer (runTime) that I want to start counting down when a Boolean is true (isRun). When my powerup collides with a player it speeds up its speed, makes isRun true and does what its supposed to except the timer isnt working. I want it to work like it the powerup only lasts 3 seconds and after 3 seconds the players speed goes normal and the Boolean turns false but the timer wont work properly. Can someone help me find my mistake in my c# code below? thanks.
public enum powerupType
{
fast
}
public powerupType type;
characterBehaviour behaviour;
float runTime;
static bool isRun = false;
void OnTriggerEnter2D(Collider2D other)
{
switch (type)
{
case powerupType.fast:
if(other.tag == "Player")
{
isRun = true;
runTime += 3;
behaviour = GameObject.Find("Player").GetComponent<characterBehaviour>();
behaviour.changeSpeed(3);
DestroyObject(this.gameObject, 0);
if(runTime <= 0)
{
isRun = false;
behaviour.changeSpeed(-3);
}
}
break;
}
}
void Update()
{
if(isRun == true)
{
runTime -= Time.deltaTime;
}
}
Your code below this line:
DestroyObject(this.gameObject, 0);
is probably inaccessible. Also - you may want to move these lines:
if(runTime <= 0){
isRun = false;
behaviour.changeSpeed(-3);
}
to
Update(){
if(isRun){
//here
}
}
Error:
-
Following code
if(runTime <= 0)
{
isRun = false;
behaviour.changeSpeed(-3);
}
to stop PowerUp is in your
OnTriggerEnter2D function. Which
only works in the frame where your
player collides with the PowerUp .
Not every frame.
-
Since you destroy your PowerUp object on colliding with player.
Above script will be destroyed too.
Hence it won’t work any further than
the frame it was destroyed.
Solution:
Put your script on the player.
In OnTriggerEnter check for PowerUp Object.
Along with decreasing timer in Update function.
Check for timer less than zero in it too. And change speed accordingly.
You are not looking for the end of the timer in the right place. You are testing if runTime is less than zero in the collision event which happens only once. I suppose you are doing so because you are destroying the object but that won’t work, runTime will always be above 0 at that time. Here is what you should do :
- Inside the switch, change the += into a = for runTime. Won’t change much, but that will make more sens. One item, one bonus.
- Do not destroy the object right away, but hide it by disabling the collider / renderer.
- Inside update, under the decrement of runTime, add the check if runtime <= 0. That’s your event check. And destroy the gameobject then.
That should do it.