I have an internal game calendar, tracking dates/month/year (in the game, not real-time) as well as a generic ‘time since game began’. I have C# objects (not monobehaviours) that I need to fire at a specific time. For example, Object1 is created on ‘Sunday, 1st January’ but when the internal calendar reaches ‘Monday, 9th January’, I need code in Object1 to run. Object2 might be created on ‘Sunday 1st January’ as well, but won’t fire till ‘Thursday 16th’ February’.
Currently, I’m using a co-routine to run the calendar itself, and I’m now looking for options on how to efficiently fire code from these objects. I know I could do it by running each object on a new co-routine and yielding, but I’m not sure I like the idea of the overhead the co-routine will create, plus it will create headaches if game time is paused as I’d have to go and pause each of the co-routines for however many objects are alive.
The only other way I know is through standard polling (ie. every time the date changes, run through the list of all objects to see if they have reached the point they need to run), but that feels like a lot of polling. Are there any other options out there?
So after some quick thinking, I have an idea.
Say you have the information (1. When to call 2. What to call 3. How to call) stored as a new class perhaps. You add all the future planned events into a list of that new class. Sort them in order of time.
Now whenever the time changes, you only need to check the first item of the list.
- If the time doesn’t match, then we
don’t do anything.
- If the time matches, then fire off whatever you
need to do for that event. Then
remove that item from the list.
- If you need to have the option of letting the user skip a whole bunch of in-game time, then just check after the time skip. Iterate through the list, do what needs to be done for the events, and then remove them from the list. Do it until you meet an event that will execute in the future.
Which means the amount of checks you need to do per time change is:
1 <= N <= number of events that need to be executed after time change
Whenever you need to add a new future event to the list, just iterate through the list and insert at the correct index after comparing the time.
Should be pretty easy to manage or even export to a file if you need to since it’s just a single list. It’s flexible too since it doesn’t depend on anything. It’s unaffected by game pausing and time skipping.
I hope I made sense. You seem like you know more about C# compared to the average user on here, so I didn’t really go into much detail. I’ll explain more if you need me to.