Time delay

I want a time delay that after X seconds after the object is created changed its Bool spawnProt to false

    public bool spawnProt = true;

    void Start () {
        // I want a X seconds delay
                 // after the X seconds have passed {
             spawnProt = false;
       }
float xSeconds = 2f;

void Start()
{
  Invoke("MyMethod", xSeconds);
}

void MyMethod()
{
  spawnProt = false;
}
3 Likes

Welcome to the forums! Please use code tags. It helps us not go insane. :slight_smile:

2 Likes

Thanks!

I will.

edit: I edited and used code tags on all my old forum posts.

2 Likes

Can I use it like this to create a infinte loop?

No, then you use InvokeRepeating:

void Start()
{
  InvokeRepeating("MyMethod", timeTillFirstFire, loopTime);
}

Itll work both ways

Even cleaner, you can use Start() as a coroutine, like so:

IEnumerator Start()
{
 float interval = 2.0f;
 while(true)
 {
  yield return new WaitForSeconds( interval);
  MyMethod();
 }
}

I prefer the latter because it feels more natural in terms of setting breakpoints when something goes wrong.

That works too… but one perk with invoke over start is the ability to stop if you want to via cancelinvoke… while(true) in start is hard to change.

True. I just associate the lifetime of such a script as being equivalent to the lifetime of the GameObject they hang on. The pattern I often use in the above is to make a new GO with the spawner script, and then when some other condition is reached, like end of level, or destruction of bonepile, destroy the GO and/or the script itself. But yeah, whatever you’re mostest comfortablest with. :slight_smile:

1 Like