Last active
October 14, 2016 18:59
-
-
Save ahmadnaser/43f1520faa295162a5f7f6120177ca12 to your computer and use it in GitHub Desktop.
Timer In C# and Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
/// <summary> | |
/// Descending Timer. | |
/// </summary> | |
public class Timer : MonoBehaviour | |
{ | |
public string startTime = ""; | |
public float delayTime = 1; | |
private string temptime;//temp time for disply only | |
private bool isRunning; | |
private bool isStarted; | |
public bool isDone; | |
public bool playAtStart; | |
public bool applyTimeToTextMeshes; | |
public TextMesh[] textmeshes; | |
public string doneEventName; | |
public GameObject doneEventObject; | |
void Awake () | |
{ | |
temptime = DataEncryption.Base64Encode (startTime); | |
ApplyToTextMeshes (); | |
} | |
void Start () | |
{ | |
if (delayTime < 0) { | |
delayTime = 1; | |
} | |
if (playAtStart) { | |
Play (); | |
} | |
} | |
private IEnumerator StartTimer () | |
{ | |
while (true) { | |
if (isRunning) { | |
if (temptime == null) { | |
break; | |
} | |
string [] decodesTime = DataEncryption.Base64Decode (temptime).Split (':'); | |
if (decodesTime == null) { | |
continue; | |
} | |
int tempm = int.Parse (decodesTime [0]);//minutes | |
int temps = int.Parse (decodesTime [1]);//seconds | |
temps--; | |
if (temps == -1) { | |
temps = 59; | |
tempm--; | |
} | |
if (tempm == 0 && temps == 0) { | |
isDone = true; | |
isRunning = false; | |
if (!string.IsNullOrEmpty (doneEventName) && doneEventObject != null) {//send message when done | |
doneEventObject.SendMessage (doneEventName); | |
} | |
} | |
string strSeconds = getStringTime (temps); | |
string strMinutes = getStringTime (tempm); | |
temptime = DataEncryption.Base64Encode (strMinutes + ":" + strSeconds); | |
if (applyTimeToTextMeshes) { | |
ApplyToTextMeshes (); | |
} | |
yield return new WaitForSeconds (delayTime); | |
} else { | |
yield return 0; | |
} | |
} | |
} | |
public static string getStringTime (int value) | |
{ | |
string strValue = ""; | |
if (value < 10) { | |
strValue += "0"; | |
} | |
strValue += value; | |
return strValue; | |
} | |
public void Reset () | |
{ | |
temptime = DataEncryption.Base64Encode (startTime); | |
} | |
public void Stop () | |
{ | |
StopCoroutine ("StartTimer"); | |
isStarted = false; | |
isRunning = false; | |
} | |
public void Pause () | |
{ | |
isRunning = false; | |
} | |
public void Play () | |
{ | |
if (!isRunning) { | |
isRunning = true; | |
if (!isStarted) { | |
temptime = DataEncryption.Base64Encode (startTime); | |
StartCoroutine ("StartTimer"); | |
isStarted = true; | |
} | |
} | |
} | |
private void ApplyToTextMeshes () | |
{ | |
if (textmeshes == null) { | |
return; | |
} | |
foreach (TextMesh tm in textmeshes) { | |
tm.text = CTime; | |
} | |
} | |
public string CTime { | |
get { return DataEncryption.Base64Decode (this.temptime);} | |
} | |
} | |
using UnityEngine; | |
using System.Collections; | |
using System; | |
using System.Linq; | |
using System.Text; | |
using System.Security.Cryptography; | |
using System.IO; | |
/// <summary> | |
/// Data encryption. | |
/// </summary> | |
public class DataEncryption : MonoBehaviour | |
{ | |
//base64 encoding | |
public static string Base64Encode (string plainText) | |
{ | |
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes (plainText); | |
return System.Convert.ToBase64String (plainTextBytes); | |
} | |
//base64 decoding | |
public static string Base64Decode (string chipherText) | |
{ | |
var base64EncodedBytes = System.Convert.FromBase64String (chipherText); | |
return System.Text.Encoding.UTF8.GetString (base64EncodedBytes); | |
} | |
//md5 encrypt | |
public static string MD5Encrypt (string toEncrypt, string securityKey, bool useHashing) | |
{ | |
string retVal = string.Empty; | |
try { | |
byte[] keyArray; | |
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes (toEncrypt); | |
ValidateInput (toEncrypt); | |
ValidateInput (securityKey); | |
if (useHashing) { | |
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider (); | |
keyArray = hashmd5.ComputeHash (UTF8Encoding.UTF8.GetBytes (securityKey)); | |
hashmd5.Clear (); | |
} else { | |
keyArray = UTF8Encoding.UTF8.GetBytes (securityKey); | |
} | |
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider (); | |
tdes.Key = keyArray; | |
tdes.Mode = CipherMode.ECB; | |
tdes.Padding = PaddingMode.PKCS7; | |
ICryptoTransform cTransform = tdes.CreateEncryptor (); | |
byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length); | |
tdes.Clear (); | |
retVal = Convert.ToBase64String (resultArray, 0, resultArray.Length); | |
} catch (Exception ex) { | |
Debug.Log (ex.Message); | |
} | |
return retVal; | |
} | |
//input validation | |
private static bool ValidateInput (string inputValue) | |
{ | |
bool notValid = string.IsNullOrEmpty (inputValue); | |
if (notValid) { | |
Debug.Log ("Invalid Input MD5"); | |
} | |
return notValid; | |
} | |
} | |
//usage | |
//1-define timer component in your class | |
public static Timer timerComp;//timer component reference | |
//2-make sure timer has been initialized in start method | |
IEnumerator Start () | |
{ | |
if (timerComp == null) { | |
timerComp = GetComponent<Timer> (); | |
} | |
timerComp.Play (); | |
yield return 0; | |
} | |
//3-make usage of timer | |
//time to stars number | |
public static void TimeToStarsLevel () | |
{ | |
int stars = 0; | |
int ctime = int.Parse (timerComp.CTime.Split (':') [1]); | |
if (ctime >= 25) { | |
stars = 3; | |
} else if (ctime >= 15 && ctime < 25) { | |
stars = 2; | |
} else if (ctime >= 0 && ctime < 15) { | |
stars = 1; | |
} | |
winStarsCount = stars; | |
} | |
//4-other usage of timer | |
if (!timerComp.isDone) | |
timerComp.Pause (); | |
5-timerComp.Stop (); | |
6-timerComp.Reset (); | |
//new way to handle timer | |
using UnityEngine; | |
using System.Collections; | |
using UnityEngine.UI; | |
[DisallowMultipleComponent] | |
public class Timer : MonoBehaviour | |
{ | |
/// <summary> | |
/// Text Component | |
/// </summary> | |
public Text uiText; | |
/// <summary> | |
/// The time in seconds. | |
/// </summary> | |
[HideInInspector] | |
public int | |
timeInSeconds; | |
/// <summary> | |
/// The progress reference. | |
/// </summary> | |
public Progress progress; | |
/// <summary> | |
/// Whether the Timer is running | |
/// </summary> | |
private bool isRunning; | |
/// <summary> | |
/// The time counter. | |
/// </summary> | |
private float timeCounter; | |
/// <summary> | |
/// The sleep time. | |
/// </summary> | |
private float sleepTime; | |
void Awake () | |
{ | |
if (uiText == null) { | |
uiText = GetComponent<Text> (); | |
} | |
///Start the Timer | |
Start (); | |
} | |
/// <summary> | |
/// Start the Timer. | |
/// </summary> | |
public void Start () | |
{ | |
if (!isRunning) { | |
timeCounter = 0; | |
sleepTime = 0.01f; | |
isRunning = true; | |
timeInSeconds = 0; | |
InvokeRepeating("Wait",0,sleepTime); | |
} | |
} | |
/// <summary> | |
/// Stop the Timer. | |
/// </summary> | |
public void Stop () | |
{ | |
if (isRunning) { | |
isRunning = false; | |
CancelInvoke(); | |
} | |
} | |
/// <summary> | |
/// Reset the timer. | |
/// </summary> | |
public void Reset () | |
{ | |
Stop (); | |
Start (); | |
} | |
/// <summary> | |
/// Wait. | |
/// </summary> | |
private void Wait () | |
{ | |
timeCounter += sleepTime; | |
timeInSeconds = (int)timeCounter; | |
ApplyTime (); | |
if (progress != null) | |
progress.SetProgress (timeCounter); | |
} | |
/// <summary> | |
/// Applies the time into TextMesh Component. | |
/// </summary> | |
private void ApplyTime () | |
{ | |
if (uiText == null) { | |
return; | |
} | |
// int mins = timeInSeconds / 60; | |
// int seconds = timeInSeconds % 60; | |
// uiText.text = "Time : " + GetNumberWithZeroFormat (mins) + ":" + GetNumberWithZeroFormat (seconds); | |
uiText.text = timeInSeconds.ToString (); | |
} | |
/// <summary> | |
/// Get the number with zero format. | |
/// </summary> | |
/// <returns>The number with zero format.</returns> | |
/// <param name="number">Ineger Number.</param> | |
public static string GetNumberWithZeroFormat (int number) | |
{ | |
string strNumber = ""; | |
if (number < 10) { | |
strNumber += "0"; | |
} | |
strNumber += number; | |
return strNumber; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment