- Home /
how to start InvokeRepeating function and timer at the same time?
I am instantiating prefab randomly using InvokeRepeating in my scene and i have also timer like this float timeRemaining = 30.0f;. I want when InvokeRepeating function start then timer should start. here is Invokereapeating
void Start () {
InvokeRepeating ("SpawnObject", 3, 1);
}
And here is Timer function
void Update()
{
//if (InvokeFunction.timerStarted == true) {
if (timeRemaining > 0) {
timeRemaining -= Time.deltaTime;
time.text = "Time: " + System.Convert.ToInt32 (timeRemaining);
}
if (timeRemaining <= 0) {
GameOver();
}
// }
}
Please help me. Thanks
Answer by ArkaneX · Mar 31, 2014 at 12:38 PM
Introduce additional variable, indicating if timer already started, and initialize it at the end of SpawnObject method (if not already initialized). Sample (might contain some typos, but general idea remains):
private bool timerStarted = false;
private void SpawnObject()
{
// your spawn code
if(!timerStarted)
{
timerStarted = true;
timeRemaining = 10;
}
}
void Update()
{
if(timerStarted)
{
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
time.text = "Time: " + System.Convert.ToInt32 (timeRemaining);
}
else
{
GameOver();
}
}
}
Answer by NDJoshi · Mar 31, 2014 at 12:56 PM
public float timer = 0.0f;
void Update ()
{
timer += Time.deltaTime;
if(timer > 30.0f)
{
GameOver();
timer = 0.0f;
}
}
No need to include any additional variables. This will work 100% as i have used this code in my project as well.
This will not work, because your timer starts instantly. According to the question, it should start after calling SpawnObject method.
Answer by YTGameDevDave · Mar 21, 2017 at 01:50 AM
Since you are using the start function, your invokerepeating method starts when script is enabled. Simply change your start function into something else and call SomethingElse(); when you start your timer.
void SomethingElse() {
InvokeRepeating ("SpawnObject", 0, 1);
}
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Have a delay after each jump, so user cant spam jump 3 Answers
Initialising List array for use in a custom Editor 1 Answer
Accelerate/Decelerate Custom Game Clock 2 Answers