Created
December 8, 2013 13:04
-
-
Save shinriyo/7857151 to your computer and use it in GitHub Desktop.
HSController(改)
AdventCalender記事用
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; | |
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"; | |
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. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment