Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Check if time has reached certain hour

Discussion in 'Scripting' started by elliotbra, Jul 1, 2023.

  1. elliotbra

    elliotbra

    Joined:
    Jul 21, 2022
    Posts:
    46
    Hi, how do I check if the system time has reached like 2 pm? Then the aysr should get gold or something.
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    You can get DateTime.Now to get the current time. You can also use DateTime to create some time to compare to, for example 2 pm. The compared value would then be smaller than 0 before the desired time and larger after it. As soon as it's larger, give out gold and use a flag to prevent this from happening twice a day.

    Code (CSharp):
    1. using System;
    2.  
    3. // Flag
    4. bool openForReward = True;
    5.  
    6. // Set up time comparison
    7. DateTime currentTime = DateTime.Now;
    8. DateTime targetTime = DateTime.Today.AddHours(14); // 2 pm
    9. int timeCompare = DateTime.Compare(currentTime, targetTime);
    10.  
    11. // Reward Check
    12. if (timeCompare > 0 && openForReward) {
    13.     Debug.Log("The current time is later than 2 PM.");
    14.     // TODO: give out coins
    15.     openForReward=False;
    16. }
    17.  
    Once the player is eligible for another reward (likely midnight), set the flag again.
     
    Last edited: Jul 1, 2023
  3. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    It's worth noting that this is not reliable, because the user can set local time to whatever they want. If you're rewarding users with something valuable you need to supply the time value from a server, or simply evaluate the passage of time on a server, and grant a reward there.
     
    Yoreki likes this.
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    Absolutely correct, if you care about cheat prevention. OP asked about just that in their previous thread. So if somebody stumbles upon this, it's probably a thread worth reading aswell.
     
    orionsyndrome likes this.
  5. lubosaliso

    lubosaliso

    Joined:
    Apr 30, 2023
    Posts:
    8
    Sure, you can create a separate time system instead of relying on "System.DateTime." For example, you can store the time data in Playerprefs. This way, instead of counting days based on "System.DateTime," you can track the usage hours based on the Playerprefs data.