Hi,
I have a problem with simple login (from here GitHub - bdodroid/SimpleScripts-LoginSystem: A simple login system for unity.)
Everything works fine but when i want to log in it says:
ArgumentNullException: Argument cannot be null.
Parameter name: s
System.Int32.Parse (System.String s) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Int32.cs:629)
Login+c__Iterator13.MoveNext () (at Assets/xxx/Demo/Login.cs:119)
Please help me, i have the same code as here so you can check
Login.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using JSONhandler;
public class Login : MonoBehaviour {
//fields and toggles using unitys new UI system. Create an InputField in the editor (right-click->ui->inputFiled) then attach it from the Hierachy.
public InputField email;
public InputField pass;
public InputField pass2;
public InputField secQ;//I just use an input field for simplicity but you could easily change this to a drop down selection box or something.
public InputField secA;
public Toggle autoLogin;
public GameObject responseText; //a ui text filed we update with information we plan on showing the user, ie. Login Success!/Email not found!
//variables we want to keep during the enitre session, like PlayerID and Username, etc.
public static int userID;
public static string userEmail;
public string URL = ""; //add the address to your php file in this line or the editor (editor overwrites whats here). example: http://yoursite.com/login.php
public string hash = "theHashCode"; //this is a secret hashcode that needs to match the one you set in your php page. See login.php for example
public void Start(){
CheckToggle ();
StartCoroutine(CheckConnection());//check the connection then run FirstRun function
}
private IEnumerator CheckConnection() {
Ping pingServer = new Ping("8.8.8.8");
float startTime = Time.time;
while (!pingServer.isDone && Time.time < startTime + 2.0f) {
yield return new WaitForSeconds(0.1f);
}
if(pingServer.isDone) {
LoginSetup(true);//function we run if we have a connection
} else {
LoginSetup(false);//function if we do not have a connection
}
}
private void LoginSetup(bool connected){
if (connected) {
//check player prefs and login if auto-login is checked
if(PlayerPrefs.HasKey("email") && PlayerPrefs.HasKey("pass")){
if(PlayerPrefs.GetInt("autoLogin") == 1){
email.text = PlayerPrefs.GetString("email");
pass.text = PlayerPrefs.GetString("pass");
LoginAccount();
}else{
email.text = PlayerPrefs.GetString("email");
}
}
} else {
if(PlayerPrefs.HasKey("userID") && PlayerPrefs.HasKey("email")){//check for stored login data
userID = PlayerPrefs.GetInt("userID");
userEmail = PlayerPrefs.GetString("email");
}else{//if we have no stored data we create a guest user and continue on to the game.
userID = -1;
userEmail = "guest@guest.guest";
PlayerPrefs.SetInt("userID", userID);
PlayerPrefs.SetString("email", userEmail);
}
//to game scene because we are not using
// Application.loadedLevel(1);
}
}
//used for Unity UI button presses.
public void LoginAccount(){
StartCoroutine(WWWSubmit("false"));
}
public void CreateAccount(){
StartCoroutine(WWWSubmit("true"));
}
public void ToggleAutoLogin(){
var toggleValue = 0;
if (autoLogin.isOn) {
toggleValue = 1;
} else {
toggleValue = 0;
}
PlayerPrefs.SetInt("autoLogin", toggleValue);
}
private void CheckToggle(){//check if we want to auto login
if (PlayerPrefs.HasKey ("autoLogin")) {
var toggleStatus = PlayerPrefs.GetInt ("autoLogin");
if (toggleStatus == 1) {
autoLogin.isOn = true;
}
}
}
IEnumerator WWWSubmit(string creatingAccount) {
var form = new WWWForm(); //create a new form for submiting
//here we add all the fields we want to send over. They must match the $_POST["namehere"] in your php script
form.AddField( "hash", hash ); //hash code must be sent! it is the only thing really securing yout login attempt
form.AddField( "email", email.text );
form.AddField( "pass", pass.text );
form.AddField("pass2", pass2.text);
form.AddField("securityQuestion", secQ.text);
form.AddField("securityAnswer", secA.text);
form.AddField ("creatingAccount", creatingAccount);
var phpData = new WWW(URL, form); //here we create a variable that submits the form data and returns the response from our php page.
yield return phpData; //we wait for the response from the server before continuing.
if (phpData.error != null) {
responseText.GetComponent<Text>().text = phpData.error; //if for some reason the www failes we report it out here.
} else {
//this is assuming you return a JSON string. You can return a single string if you want but JSON is much more flexible, especially when dealing with arrays.
var parsedData = JSON.Parse(phpData.text);
if(parsedData != null){//if we get a JSON string back
userEmail = parsedData[1]["email"]; //an issue where JSON keeps returning slot 0 as empty. Working on it, but in the mean time 1 is the first slot.
userID = int.Parse(parsedData[1]["ID"]);
responseText.GetComponent<Text>().text = "CONNECTED";
SetPlayerPrefs();
}else{//if we dont get a JSON string back
responseText.GetComponent<Text>().text = phpData.text; //show the returned string. Login/Failed etc.
}
phpData.Dispose(); //clear the stored form data
}
}
private void SetPlayerPrefs(){//add whatever variables you want to store on the device itself here. Im using it here to store auto login detials.
PlayerPrefs.SetInt("userID", userID);
PlayerPrefs.SetString("email", userEmail);
PlayerPrefs.SetString("pass", pass.text);
}
}
JSONhandler.cs
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace JSONhandler
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem){ }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
protected JSONBinaryTag valueType = JSONBinaryTag.Value;
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public virtual IEnumerable<string> Keys { get { yield break; } }
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value,out v))
return v;
return 0;
}
set
{
Value = value.ToString();
valueType = JSONBinaryTag.IntValue;
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value,out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
valueType = JSONBinaryTag.FloatValue;
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value,out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
valueType = JSONBinaryTag.DoubleValue;
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value,out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
valueType = JSONBinaryTag.BoolValue;
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName,Token);
}
TokenName = "";
Token = "";
if (stack.Count>0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i+1,4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public void SaveToFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using(var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex<0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex<0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get{ return new JSONLazyCreator(this);}
set{ m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for(int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey,value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public override IEnumerable<string> Keys
{
get
{
foreach (var key in m_Dict.Keys)
yield return key;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach(string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
bool asString = false;
switch (valueType) {
default:
asString = true;
break;
case JSONBinaryTag.BoolValue:
case JSONBinaryTag.IntValue:
case JSONBinaryTag.DoubleValue:
case JSONBinaryTag.FloatValue:
asString = false;
break;
}
if (asString) {
return "\"" + Escape(m_Data) + "\"";
}
else {
return m_Data;
}
}
public override string ToString(string aPrefix)
{
return ToString ();
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
public static class test
{
public static JSONClass TestClass() {
JSONClass container = new JSONClass();
JSONClass subContainer = new JSONClass();
JSONArray subArray = new JSONArray();
subContainer["key1" ] = "value1";
subArray [0 ].AsInt = 0;
subArray [1 ].AsInt = 1;
subArray [2 ] = "2";
subArray [3 ] = "3";
container ["boolean true" ].AsBool = true;
container ["boolean false"].AsBool = false;
container ["int 0" ].AsInt = 0;
container ["int 1" ].AsInt = 1;
container ["float 0" ].AsFloat = 0.0f;
container ["float 1" ].AsFloat = 1.0f;
container ["double 0" ].AsDouble = 0.0;
container ["double 1" ].AsDouble = 1.0;
container ["string hello" ] = "hello";
container ["string 0" ] = "0";
container ["class" ] = subContainer;
container ["array" ] = subArray;
return container;
}
public static string TestString() {
return TestClass().ToString();
}
public static bool HasExpectedOutput() {
string actualOutput = TestString();
string expectedOutput = "{\"boolean true\":true, \"boolean false\":false, \"int 0\":0, \"int 1\":1, \"float 0\":0, \"float 1\":1, \"double 0\":0, \"double 1\":1, \"string hello\":\"hello\", \"string 0\":\"0\", \"class\":{\"key1\":\"value1\"}, \"array\":[ 0, 1, \"2\", \"3\" ]}";
return actualOutput == expectedOutput;
}
}
}
accounts.php
<?
/////////////////////////
//if you are having promblems please make sure that the table and column names in your database match the ones being used in the sql below
/////////////////////////
// Connection INFO ----------------------------------------------------------
//FILL THIS OUT
$host = "localhost"; //host location (use localhost if your mysql database is hosted on the same machine/account as your site)
$user = ""; //username
$password = ""; //password here
$dbname = ""; //your database
$connection = mysqli_connect($host,$user,$password,$dbname) or die("Error " . mysqli_error($connection));
//--------------------------------------------------------------------------------------------------------------
// Here we protect ourselves from SQL Injection and convert the string to MD5 if we want
function anti_injection_login($sql, $formUse, $encrypt){
$sql = preg_replace("/(from|select|insert|delete|where|drop table|show tables|,|'|#|\*|--|\\\\)/i","",$sql);
$sql = trim($sql);
$sql = strip_tags($sql);
if(!$formUse || !get_magic_quotes_gpc())
$sql = addslashes($sql);
if($encrypt){
$sql = md5(trim($sql));
}
return $sql;
}
//--------------------------------------------------------------------------------------------------------------
$unityHashPass = anti_injection_login($_POST["hash"],true,false);
$phpHashPass = "theHashCode"; // must be the same code you set in unity
$email = anti_injection_login($_POST["email"],true,false);
$pass = anti_injection_login($_POST["pass"],true,true);
$pass2 = anti_injection_login($_POST["pass2"],true,true);
$secQ = anti_injection_login($_POST["securityQuestion"],true,false);
$secA = anti_injection_login($_POST["securityAnswer"],true,false);
$creatingAccount = $_POST["creatingAccount"];
//check if our hashpass's are the same and if an email and password where sent.
if ($unityHashPass != $phpHashPass || !$email || !$pass){
echo "Username or password can not be empty.";
} else {//if they are the same
if($creatingAccount == "true"){//if we are creating an account. Variable is sent from the WWWSubmit function in Login.cs in Unity
$SQL = "SELECT email FROM Accounts WHERE email = '" . $email . "'";
$result_id = mysqli_query($connection, $SQL) or die("Error in Selecting " . mysqli_error($connection));
$results = mysqli_num_rows($result_id);
if($results > 0) {
echo "That account already exists.";
}else{
if(!$secQ || !$secA || !$pass2){
echo "Please fill out all fields.";
}else{
if($pass == $pass2){
$SQL = "INSERT INTO Accounts (`email`, `password`, `secretQuestion`, `answer`)
VALUES ('". $email ."', '". $pass ."', '". $secQ ."','". $secA ."')";
$result = mysqli_query($connection, $SQL) or die("DATABASE ERROR!");
echo "Account created.";
}else{
echo "Passwords must match";
}
}
}
}else{
$SQL = "SELECT * FROM Accounts WHERE email = '" . $email . "'";
$result = mysqli_query($connection, $SQL) or die("Error in Selecting " . mysqli_error($connection));
$results = mysqli_num_rows($result);
$temparray[] = array();
while($row = mysqli_fetch_assoc($result)){
$temparray[] = $row;
$comPass = $row['password'];
}
if($results) {
if(!strcmp($pass,$comPass)) {
echo json_encode($temparray);
} else {
echo "Login or password incorrect.";
}
} else {
echo "Email doesnt exist.";
}
}
}
mysql_close();
?>
Thank You!
