Hey guys,
I have about 50 blocks of code identical to this…
private int counter = -1; … void FixedUpdate() { if (counter !=-1){ counter–; if (counter==-1) doSomething; } }
This way, if I want to perform a delayed function, I just set the counter to 60 or something. Is there a built-in way to provide this sort of functionality, with less code? I would prefer not to use IEnumerators.
Invoke can be used. Coroutines and WaitForSeconds gives far more control. There is no particular reason to be scared of coroutines. In most cases they will perform better then the code you have provided.
Note your example counts down physics ticks, not time. It might break things if the time step ever changes.
Well, you could call Invoke, with the name of the function you want to call and the delay (in seconds) before you want to call it.
In my projects, though, I have a couple of solutions I typically use. One is a little class that invokes a UnityEvent after a specified delay. I can stick that in a chain with other events. The other is the little utility class below.
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
public class CallLater : MonoBehaviour {
#region Static Stuff
public delegate void Callback(object arg);
class PendingCallback {
public Callback callback;
public object argument;
public float timeDue;
}
/// <summary>
/// Do something (defined by arbitrary callback) after a delay.
/// </summary>
/// <param name="secondsDelay">Number of seconds to wait before invoking the callback.</param>
/// <param name="callback">Callback to invoke.</param>
/// <param name="callback">Optional argument to supply to the callback.</param>
public static void DoAfter(float secondsDelay, Callback callback, object argument=null) {
PendingCallback pd = new PendingCallback();
pd.callback = callback;
pd.argument = argument;
pd.timeDue = Time.time + secondsDelay;
GetInstance().pendingCallbacks.Add(pd);
}
static CallLater _instance;
static CallLater GetInstance() {
if (_instance == null) {
GameObject obj = new GameObject();
obj.name = "CallLater";
_instance = obj.AddComponent<CallLater>();
}
return _instance;
}
// We keep our pending callbacks NOT static, but on the instance.
List<PendingCallback> pendingCallbacks = new List<PendingCallback>();
#endregion
//--------------------------------------------------------------------------------
#region MonoBehaviour Events
void Awake() {
_instance = this;
}
void Update() {
IEnumerable<PendingCallback> dueE = pendingCallbacks.Where(el => Time.time > el.timeDue);
if (!dueE.Any()) return;
List<PendingCallback> due = dueE.ToList<PendingCallback>();
foreach (PendingCallback pd in due) {
pd.callback(pd.argument);
pendingCallbacks.Remove(pd);
}
}
#endregion
}
This gives me a “CallLater” function I can use wherever I need it, by passing in the code I want to do later as a delegate. Here’s an example call.