Check System Time and execute function

Hi,

I have a function I want to trigger based on current real time.

For example, there is an event that happening at 2pm and I want to execute a function to play a video.

I have create this code but I am not sure if this is the right way

 DateTime eventTime;

        private void Update()
        {
            if(currentTime.Date != eventTime.Date)
                return;

            if(currentTime.Hour == eventTime.Hour && currentTime.Minute == eventTime.Minute)
            {
                PlayVideo();
            }
        }

If this a good way to do the code?

I haven’t had a proper look at DateTime but I expect that it includes very precise float values meaning it becomes incredibly unlikely that two times are ever equal (unless they came from the same source).

What you can do is to check whether the eventTime has elapsed:

DateTime eventTime;
bool videoHasBeenPlayed = false;
 
private void Update()
{
    if( !videoHasBeenPlayed && currentTime > eventTime )
    {
        videoHasBeenPlayed = true;
        PlayVideo();
    }
}

This could make perfect sense to you but for avoidance of doubt, I’ll explain it a little - usually the > sign test whether the former value is larger however DateTime objects use the > operator to test whether the former value is later. I’ve opted for a check that we’re passed your eventTime because it doesn’t take into account the Update step time which is about 16 milliseconds for a 60FPS game. We use the videoHasBeenPlayed flag to ensure we only call the PlayVideo function once, setting this to true inside the if-statement makes sure that we can’t enter that if-statement again (without resetting that videoHasBeenPlayed back to false). You might have come across it while working on this but the bottom if-statement in your code will evaluate to true for a while minute causing PlayVideo to be called a lot.

Hope this helps! Let me know if not