I’m creating a delayed function manager so that you can call TimeManager.DelayedCall(uniqueid, delay, action) to make action get invoked in delay seconds. However, I’m running into some trouble. Here’s the code so far.
private static Dictionary<string, object> delays = new Dictionary<string, object>();
public static void Think(float dt)
{
timestep = dt * timescale;
time += timestep;
foreach (KeyValuePair<string, object> kv in delays)
{
if (time > kv.Value.ourtime)
{
kv.Value.action();
}
}
}
public static void DelayedCall(string id, float delay, Action a)
{
delays[id] = new { ourtime = time + delay, action = a };
}
This code doesn’t compile. Because I’m converting the anonymous type from the DelayedCall function to an object, I cannot get the variables ourtime and action from it in the Think function! Does anyone know how to fix this, or how to do this in a better way?
EDIT Corrected some details here. See comment by Matti Virkkunen below.
Your anonymous type only has scope in the method where you create it. You cannot get the properties in the think function, because once you cast it into the object
and save it in the dictionary the properties you set are gone.you cannot cast it back to the original type created by the compiler, so you cannot access the properties you set except indirectly via reflection.Why do you need to use anonymous types and object type at all?
Based on the code posted I would just create a DelayData object that has all the properties you need to set, create and store instances of DelayData in the dictionary, and then use that object directly from the dictionary.