The question is answered, right answer was accepted Thx <3
Question about delay
Hi, im trying to increase the mouvement speed object in a defined period like 10s. I wonder how to integrate a notion of delay. I was thinking about a counter and a function while, but i dont know how to specify that the counter must be incremented every second and how Or maybe is there an another function for that ?
Answer by MacDx · Dec 07, 2017 at 05:49 PM
Coroutines are the answer, they're excellent for stuff like this. The allow you to delay the execution of code, and they run in "parallel" to the update method. I'll give you a small example
void Start()
{
StartCoroutine(Counter(10));
}
private IEnumerator Counter(int countLimit)
{
int count = 0;
while(count < countLimit)
{
yield return new WaitForSeconds(1f); // 1 second delay
//Do stuff after the delay
print("Increasing movement speed");
print("Count: " + count);
}
}
So this creates a counter that gets increased every second. In this example I start the coroutine at Start however you can start a coroutine wherever and whenever you want (Careful with doing it inside an Update method because you could potentially create a ton of coroutines, one each frame at 60 frames per second, that is a lot and they will all run in "parallel" which can cause and will probably cause unexpected behaviour so be warned, if you mean to only use one at a time, then make sure only one gets started). There's a lot of stuff you can do with coroutines, so I suggest you to investigate them a little bit further. https://docs.unity3d.com/Manual/Coroutines.html
Hope this helps!
Thanks for help ! I tried to use your example script but nothing happens on my screen. I can see a function print, that's why i wonder. Im trying to learn about this Coroutine function on your link
Nothing happens on screen because there is no code there that will make something happen on screen, you'll only get console prints. But that's the point, it is just an example, you should be able to fill/use that with the actual code for your game.
Yep I understand now, thanks ! if you can help me for this 2nd problem that would be really nice, otherwise ill do without :x. I have something like that in my script, but something is wrong with my boolean, that said me unexpected symbol 'alright'.A big thank you if you help me ... private bool alright = true; void Update(){ if ( (Y) && (alright == true) ){ StartCoroutine( delay () ) } IEnumerator delay() { yield return new WaitForSeconds(10f) alright = true; }