Home > database >  Am I on the right track- Unity C# Events at a certain time
Am I on the right track- Unity C# Events at a certain time

Time:12-01

let me know if i'm on the right track of this-- i want to trigger certain events at a certain time in the game. For instance say at 10AM each morning I will have event a, b, and c happen. My current code is something like:

public static Action<int> morningEvents = delegate { };

so I declare an action and then some methods to check time and trigger the action; for example

void CheckTime()
{
  check if current time is 10AM then call morningEvents()
}

and I will register the the events a b c to the action

morningEvents  = event a;
morningEvents  =event b;
morningEvents  =event c;

Is it possible to achieve my goals with the logic above? Also I don't know what parameters I need to pass in Action< >. I know the default is int but have no idea why.

CodePudding user response:

You could use events as in code below, but this is certainly not the best example how to do it. In such "simple example", I wouldn't create events - just for the reason that it is so simple.

public class MySampleClass : MonoBehaviour
{
    public delegate void CertainTimeReachedHandler();
    public event CertainTimeReachedHandler tenAmTimeReached;
    private bool wasReachedToday = false;

    void Start()
    {
        tenAmTimeReached  = ShowClock();
        tenAmTimeReached  = b();
        tenAmTimeReached  = c();
    }

    void Update()
    {
        var now = DateTime.Now;
        var tenAm = DateTime.Today.AddHours(10);

        if( (!wasReachedToday) && (now > tenAm) && (now < tenAm.AddSeconds(1)) )
        {
            wasReachedToday = true;
            tenAmTimeReached?.Invoke();
        }
    }

    private void ShowClock() { }
    private void b() { }
    private void c() { }
}

If I would want to create it for "production level", I would create:

  • Class that represents relation between condition & time - when it should be fired (DT from, DT to, how many times per day it can be fired, etc.) ~ TaskDTCondition
  • Class that stores all conditions stores events for them invokes those events on condition validity (DT reach) ~ TaskScheduler
  • In my classes where I want to have such checks, I would call TaskScheduler, ask for an event at specific date and register my private method to be invoked on that event.

For the above, there is likely to be existing some library already, try look around a little. Maybe even in Unity framework (that I'm not aware of). Anyway, this is really broad and if you would like to have more details, you would want to put on different SE site.

  • Related