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?
-
\$\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\$– MangataMay 7 at 2:04
1 Answer
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.
-
\$\begingroup\$ Does this check _shouldDoThing every frame if it's false? \$\endgroup\$ May 7 at 16:12
-
\$\begingroup\$ It does, as you can verify by running the code. \$\endgroup\$– DMGregory ♦May 7 at 16:13