Skip to content

Instantly share code, notes, and snippets.

@loicteixeira
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loicteixeira/ab49bafef1db61733b68 to your computer and use it in GitHub Desktop.
Save loicteixeira/ab49bafef1db61733b68 to your computer and use it in GitHub Desktop.
Retrieve GameJolt user credentials from Unity for WebPlayer and WebGL builds (and simulate in the Editor)
using UnityEngine;
using System.Collections;
public class GetUserFromWeb : MonoBehaviour
{
// Set those up in the inspector if you want to simulate the GetFromWeb behaviour in within the Editor.
public string debugUser;
public string debugToken;
void Awake()
{
GetFromWeb();
}
// Ask the webpage for the credentials.
void GetFromWeb()
{
#if UNITY_EDITOR
if (!string.IsNullOrEmpty(debugUser) && !string.IsNullOrEmpty(debugToken))
{
OnGetFromWeb(string.Format("{0}:{1}", debugUser, debugToken));
}
#elif UNITY_WEBPLAYER
Application.ExternalCall ("GJAPI_AuthUser", gameObject.name, "OnGetFromWeb");
#elif UNITY_WEBGL
Application.ExternalEval(string.Format(@"
var qs = location.search;
var params = {{}};
var tokens;
var re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {{
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}}
var message;
if ('gjapi_username' in params && params.gjapi_username !== '' && 'gjapi_token' in params && params.gjapi_token !== '') {{
message = params.gjapi_username + ':' + params.gjapi_token;
}}
else {{
message = '';
}}
SendMessage('{0}', 'OnGetUserFromWeb', message);
", gameObject.name));
#else
Debug.Log("GJAPIHelper: The method \"GetFromWeb\" can only be called from WebPlayer or WebGL builds.");
#endif
}
// Read the webpage response.
public void OnGetFromWeb(string response)
{
if (response != string.Empty)
{
var credentials = response.Split(new char[] { ':' }, 2);
Debug.Log(string.Format("User: {0} - Token: {1}", credentials[0], credentials[1]));
}
else
{
Debug.Log("User: Guest");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment