0
\$\begingroup\$

I'm trying to make my player launch an object every 3 seconds when a bool is true but I can't InvokeRepeating in Update, Awake, or Start without losing control of the function. How can I do this?

\$\endgroup\$
2
  • \$\begingroup\$ What do mean by "losing control of the function"? \$\endgroup\$
    – DMGregory
    May 6 at 22:53
  • \$\begingroup\$ Maybe what you need is CancelInvoke? \$\endgroup\$
    – Mangata
    May 7 at 2:04

1 Answer 1

0
\$\begingroup\$

Here's one way to do it:

bool _shouldDoThing;
Coroutine _periodicAction;

IEnumerator DoThingPeriodically() {
    var delay = new WaitForSeconds(3f);

    while(true) {
        if (_shouldDoThing) {
            DoTheThing();
            yield return delay();
        } else {
            yield return null;
        }
    }
}


void Start() {
    _periodicAction = StartCoroutine(DoThingPeriodically());
}

This will call DoTheThing() once every three seconds (approximately) while the boolean is true. When the boolean is false, it will fall back to waiting until it is true again, then calling DoTheThing() immediately when it goes back to true if it's been at least three seconds.

If you ever want to stop the action, you can call StopCoroutine(_periodicAction) to abort it.

\$\endgroup\$
2
  • \$\begingroup\$ Does this check _shouldDoThing every frame if it's false? \$\endgroup\$
    – user253751
    May 7 at 16:12
  • \$\begingroup\$ It does, as you can verify by running the code. \$\endgroup\$
    – DMGregory
    May 7 at 16:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .