Select Page

Unity3d Internet Time and Date Guide

Score 85%

Welcome to my Unity3d guide on getting accurate time and date from the internet

 

Option 1: skip the work and get the asset: Unity Asset Store

Option 2: continue reading

Overview

What this guild will cover:

  • Writing a single php script to give us the time
  • Retrieving the time and date within unity (a single www)
  • Using a TimeManager Script (You can use in multiple project without recoding anything)
  • Creating a daily and hourly reward system
  • A fully Independent Time System you can import into other Projects.

Why would you need a server time and date?

A secure 24 hour timer is very important for your Unity3d Project. It is a fact that players enjoy coming back to a game  simply for the daily rewards, but without a proper time system in place, you game can be easily hacked. If your daily or hourly reward system is checking the platform time, then all the player has to do is change the time of their computer or phone and “Tada!”. With a internet base time and date, you can create a daily leaderboard by simply saving the players score and date, then return the scores matching the current or previous date.

 

Unity Internet Time and Date – setup php

Get time and date from php 2017

First thing we will need is a simple php file to fetch the server time from and drop it into unity. We use only one php file, which will return the time and date, then we will split the data and separate the time form the date in Unity. The php code we will use to get time and date from the internet is :

<?php
 date_default_timezone_set('US/Eastern');
 $currenttime = date("m-d-Y H:i:s");
 list($ddd,$ttt) = split(' ',$currenttime);
 echo "$ddd/$ttt\n";
?

If you get an error with this php script. try replaceing “split” with the word “explode” this is the new way of splitting data in php5

you need a website or server to place this php some where out there on the web. I put mine in the back end of my WordPress site within my Cpanel. Keep a record of the direct url to that php file.

 

Unity Internet Time and Date – create time manager

Manage the time and date from the internet with unity:

Lets step over into unity with the path of our php file. We will create a new script and call it “TimeManager”  This will be created using a Singleton pattern (look it up if you don’t know what it is). We want to make this TimeManager as independent as possible so that you can wrap it up after you’re done and reuse it within other projects. Here is the code we are going to use to manage the time and date from the internet with unity:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimeManager : MonoBehaviour {
    /* 
          necessary variables to hold all the things we need.
        php url
        timedata, the data we get back
        current time
        current date
    */ 

    public static TimeManager sharedInstance = null;
    private string _url = "http:\\Path_to_php";
    private string _timeData;
    private string _currentTime;
    private string _currentDate;


    //make sure there is only one instance of this always.
    void Awake() {
        if (sharedInstance == null) {
            sharedInstance = this;
        } else if (sharedInstance != this) {
            Destroy (gameObject);  
        }
        DontDestroyOnLoad(gameObject);
    }


    //time fether coroutine
    public IEnumerator getTime()
    {
        Debug.Log ("==> step 1. Getting info from internet now!");
        WWW www = new WWW (_url);
        yield return www;
        Debug.Log ("==> step 2. Got the info from internet!");
        _timeData = www.text;
        string[] words = _timeData.Split('/');    
        //timerTestLabel.text = www.text;
        Debug.Log ("The date is : "+words[0]);
        Debug.Log ("The time is : "+words[1]);

        //setting current time
        _currentDate = words[0];
        _currentTime = words[1];
    }


    //get the current time at startup
    void Start()
    {
        Debug.Log ("==> TimeManager script is Ready.");
        StartCoroutine ("getTime");
    }

    //get the current date
    public string getCurrentDateNow()
    {
        return _currentDate;
    }


    //get the current Time
    public string getCurrentTimeNow()
    {
        return _currentTime;
    }


}

Consider investing in learning more

Unity avoid time cheat

Unity Internet time and date example script

The hard part is done. We now have everything setup how we want them. At this point we can make prefabs that will communicate this the “TimeManager” script from anywhere in the game.

Now that you have made a unhackable timer in unity, the rest is very simple. You can use “TimeManager.sharedInstance.getCurrentTimeNow()” to get the current time. I suggest calling the getTime function first and use coroutine to make sure it download the new time first before setting any text or variables. for example:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DailyEventTimer : MonoBehaviour {
    public Button timerButton;
    public Text timeLabel;
    public string StartTime;
    public string EndTime;
    private double tcounter;
    private TimeSpan eventStartTime;
    private TimeSpan eventEndTime;
    private TimeSpan currentTime;
    private TimeSpan _remainingTime;
    private string Timeformat;
    private bool timerSet;
    private bool countIsReady;
    private bool countIsReady2;


    void Start () {
        eventStartTime = TimeSpan.Parse (StartTime);
        eventEndTime = TimeSpan.Parse (EndTime);
        StartCoroutine ("CheckTime");
    }


    private IEnumerator CheckTime()
    {
        Debug.Log ("==> Checking the time");
        timeLabel.text = "Checking the time";
        yield return StartCoroutine (
            TimeManager.sharedInstance.getTime()
        );
        updateTime ();
        Debug.Log ("==> Time check complete!");

    }



    private void updateTime()
    {
        currentTime = TimeSpan.Parse (TimeManager.sharedInstance.getCurrentTimeNow ());
        timerSet = true;
    }



    void Update()
    {
        if (timerSet) 
        {
            if (currentTime >= eventStartTime && currentTime <= eventEndTime) 
            {//this means the event as already started and players can click and join
                _remainingTime = eventEndTime.Subtract(currentTime);
                tcounter = _remainingTime.TotalMilliseconds;
                countIsReady2 = true;

            } else if (currentTime < eventStartTime) 
            {//this means the event had not started yet for today
                _remainingTime = eventStartTime.Subtract(currentTime);
                tcounter = _remainingTime.TotalMilliseconds;
                countIsReady = true;
            } else 
            {//the event as already passed
                disableButton("Event is over, comeback tomorrow");
            }
        }

        if (countIsReady) { startCountdown ();}
        if (countIsReady2) { startCountdown2 ();}
    }

    //setup the time format string
    public string GetRemainingTime(double x)
    {
        TimeSpan tempB = TimeSpan.FromMilliseconds(x);
        Timeformat = string.Format("{0:D2}:{1:D2}:{2:D2}", tempB.Hours, tempB.Minutes, tempB.Seconds);
        return Timeformat;
    }


    private void startCountdown()
    {
        timerSet = false;
        tcounter-= Time.deltaTime * 1000;
        disableButton("Starting Soon : " + GetRemainingTime(tcounter));

        if (tcounter <= 0) {
            countIsReady = false;
            validateTime ();
        }
    }

    private void startCountdown2()
    {
        timerSet = false;
        tcounter-= Time.deltaTime * 1000;
        enableButton("Event Started! Time Remaining : " + GetRemainingTime(tcounter));

        if (tcounter <= 0) {
            countIsReady2 = false;
            validateTime ();
        }
    }

    //enable button function
    private void enableButton(string x)
    {
        timerButton.interactable = true;
        timeLabel.text = x; 
    }


    //disable button function
    private void disableButton(string x)
    {
        timerButton.interactable = false;
        timeLabel.text = x;
    }

    //validator
    private void validateTime()
    {
        Debug.Log ("==> Validating time to make sure no speed hack!");
        StartCoroutine ("CheckTime");
    }

}

In this example above, I made a button with a text label to display the time. This game object will be your daily event user interface of your design. Simply slap this script on to it, assign the four public variables to the correct elements of your game object. Assign your button, timer label, then simply input the start and end time within the unity project inspector (use format 00″00″00).

Without the use of PlayerPrefs, this script will keep an accurate time of any daily events. It will let you know how long until the event starts, and how long before it ends.

Conclusion

Daily and hourly rewards have become essential to the mobile game industry, and should be used when every they can. The only issue is creating a timer that is not local to the device. The answer is to simply us the internet. For those of you asking “How to create a unity server base timer”, “How to create a daily reward system with Unity”or simply trying to know “How to build a unity countdown timer”, then I hope this answers your questions, or get you on the right track.

Review

85%

85%

About The Author

Leaton Mitchell

Being smart doesn't count if you do not share your knowledge.

1 Comment

  1. last update was 4/15/2018