Hi,
Ok, great, so the issue is that the object is being destroyed then and as such the coroutine is lost with it.
I would suggest moving the coroutine code to a more appropriate object from an object orientated perspective, for example…
I am assuming that the speed up relates to the paddle, e.g. you make it move a bit faster for a short period of time.
Assuming so, SpeedUp()
should really be a method on the Paddle, as it is a behaviour of the Paddle.
I would probably also move the collision test also, rather than having that on the falling power-up game object, I’d place it on the Paddle. You could incorporate a switch() statement and use an enum to then determine which power-up the Paddle has collided with, and from that, call the relevant method on the Paddle itself, e.g.
// pop this within the collision detection on the paddle
// assumes "x" is the other game object that made the collision, e.g. the falling power-up
// and that your public variable, exposing the Paddle's PowerUp enumerator is called "type"
switch (x.type)
{
case PowerUp.Type.SpeedUp:
SpeedUp();
break;
case PowerUp.Type.SpeedDown:
SpeedDown();
break;
}
To incorporate this the falling power-up would need to know what type of power-up it was, so a PowerUp script could be attached to it. This could either have a public variable which you then set to be one of the PowerUp Type
enumerators (SpeedUp, SpeedDown etc), or, a private variable but with a public property (at this stage you are probably more used to exposing the data via a public variable so maybe stick with that. e.g.
using UnityEngine;
public class PowerUp : MonoBehaviour
{
public enum Type { None, SpeedUp, SpeedDown };
public Type type;
}
You could then use prefabs in order to create different power-ups as you can set their type through that exposed variable.
The SpeedUp()
method can contain the coroutine call, which will facilitate the 3 second life time of the power-up, the Paddle object is not destroyed unless another level is loaded, in which case the fact that the power-up has now ended doesn’t matter anyway.
The shredder at the bottom of the game should destroy any falling power-ups that reach it, so I think what you already have above should still handle that.
The only thing that would leave is then destroying the power-up when it makes contact with the Paddle, by moving SpeedUp()
method and coroutine call to the Paddle as describe above, simply calling Destroy()
on the power-up upon the collision will now be ok, as the Paddle will handle the rest. Just make sure that you use the Destroy()
method after calling SpeedUp()
on the Paddle.
Hope this helps
Updated Sat Jun 24 2017 18:28
I updated the above with a couple of small code examples.
Updated Sat Jun 24 2017 18:44
Updated the small code examples to not be syntactically incorrect!.. lol…