- Home /
Random timers in a 2d game
I have a game object that every couple of seconds i want it to change to change state, then the timer starts again and the loop is repeated till the game is closed. I got the sprite switching animation working but i cant find a solution to this sort of timer.
Thanks in advance
Answer by theInsomniacGameMaker · Sep 10, 2018 at 10:05 AM
Hi @Swize! There are a couple of ways you can approach this problem. I will tell you the easiest way.
Use InvokeRepeating.
InvokeRepeating is a function that keeps on calling a certain function after every x-seconds.
This is the link to the scripting reference.
Use this as a reference to achieve the desired effect.
I would suggest calling InvokeRepeating in the Start function (like they do in the example).
The InvokeRepeating function takes 3 parameters.
Name of the function that is to be called.
Delay for calling the function for the first time.
After the first call to function what should be the time interval.
Feel free to ask me any other questions you have!
Thanks a lot ill will definitely use this :D, but how would i get the character to change back to his previous state, because i assume that after the timer will finish he will remain in the state that is declared in the function.
Sorry for the late reply. Could you make another thread of question and explain the second problem in detail so I can help you. Thanks!
Answer by Hellium · Sep 10, 2018 at 10:08 AM
private float timer = 0 ;
public float Duration = 10;
public float[] Steps = new float[]{2, 4, 6, 8};
private int stepIndex ;
private void Update()
{
timer += Time.deltaTime ;
if( timer > Duration )
{
timer = 0 ;
stepIndex = 0 ;
// Timer has looped : do something
}
else if( stepIndex < Steps.Length && timer > Steps[stepIndex] )
{
stepIndex++ ;
// Step : do something
}
}
Your answer
Follow this Question
Related Questions
How to make "circle" sprite’s border more smooth? 1 Answer
Normal map on 2D sprite screwed it up.,Applying material with normal map on 2D sprite screwed it up. 2 Answers
Adding items to an inventory by clicking on them? 1 Answer
My player is not rotating upwards when it moves upwards. Any advice? 1 Answer
How to destroy a object when it's off screen and re-instantiate it when it gets back on screen 0 Answers