Skip to content

Instantly share code, notes, and snippets.

@shinriyo
Last active Dec 30, 2015
Embed
What would you like to do?
using UnityEngine;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
public class HSController : MonoBehaviour
{
private string secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server
public string addScoreURL = "http://localhost/unity_test/addscore.php?"; //be sure to add a ? to your url
public string highscoreURL = "http://localhost/unity_test/display.php";
private string nameStringToEdit = "";
private string scoreStringToEdit = "";
void Start ()
{
StartCoroutine (GetScores ());
}
public string CalculateMD5Hash (string input)
{
// step 1, calculate MD5 hash from input
MD5 md5 = System.Security.Cryptography.MD5.Create ();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes (input);
byte[] hash = md5.ComputeHash (inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < hash.Length; i++)
{
sb.Append (hash [i].ToString ("X2"));
}
return sb.ToString ();
}
// remember to use StartCoroutine when calling this function!
IEnumerator PostScores (string name, int score)
{
//This connects to a server side php script that will add the name and score to a MySQL DB.
// Supply it with a string representing the players name and the players score.
string hash = CalculateMD5Hash (name + score + secretKey);
string post_url = addScoreURL + WWW.EscapeURL (name) + "/" + score + "/" + hash + "/";
// Post the URL to the site and create a download object to get the result.
WWW hs_post = new WWW (post_url);
yield return hs_post; // Wait until the download is done
if (hs_post.error != null)
{
print ("There was an error posting the high score: " + hs_post.error);
}
}
// Get the scores from the MySQL DB to display in a GUIText.
// remember to use StartCoroutine when calling this function!
IEnumerator GetScores ()
{
gameObject.guiText.text = "Loading Scores";
WWW hs_get = new WWW (highscoreURL);
yield return hs_get;
if (hs_get.error != null)
{
print ("There was an error getting the high score: " + hs_get.error);
}
else
{
gameObject.guiText.text = hs_get.text; // this is a GUIText that will display the scores in game.
}
}
void OnGUI ()
{
nameStringToEdit = GUI.TextArea (new Rect (10, 10, 200, 40), nameStringToEdit, 200);
scoreStringToEdit = GUI.TextArea (new Rect (10, 70, 200, 40), scoreStringToEdit, 200);
if (GUI.Button (new Rect (20, 120, 80, 20), "Post"))
{
StartCoroutine (PostScores (nameStringToEdit, int.Parse(scoreStringToEdit)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment