Hey guys. So I want to save the users score after the game is over and push it to my database at parse.com. So basically when the game is over, the user has to input his username and click on a save button. the problem is, that my function is trying to upload the users score the whole time and I getting an error for missing username. Ofc I do because the game wasnt over and the textfield for the username didnt show up at this time. This is my code. I hope you guys can help me with this.
using System.Collections;
using Parse;
public class Timer : MonoBehaviour {
public GUIStyle Font;
public float timer = 20;
private string username;
//Timer
void Update () {
if (timer > 0) {
timer -= Time.deltaTime;
}
else {
timer = 0;
}
}
void OnGUI()
{
GUI.Box (new Rect (350, 12, 48, 36), GUIContent.none);
GUI.Box (new Rect (350, 12, 48, 36), "" + timer.ToString ("0"), Font);
if (timer == 0) {
username = GUI.TextField (new Rect (200, 200, 200, 20), username, 25);
if (GUI.Button (new Rect (200, 250, 50, 20), "Save Score")) { //restart button mit score save
SaveObject (username);
Application.LoadLevel ("level1");
}
}
}
// Score auf Parse hochladen
void SaveObject (string user) {
ParseObject gameScore = new ParseObject ("GameScore");
levelSystem level = GameObject.Find ("_Main Camera").GetComponent<levelSystem> ();
gameScore ["score"] = level.sumExp;
gameScore ["playerName"] = username;
gameScore.SaveAsync ();
}
}
P.S. The error I am getting while playing is: “NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUI.DoTextField (Rect position, Int32 id, UnityEngine.GUIContent content, Boolean multiline, Int32 maxLength, UnityEngine.GUIStyle style) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/GUI.cs:539)
UnityEngine.GUI.TextField (Rect position, System.String text, Int32 maxLength) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/GUI.cs:445)
Timer.OnGUI () (at Assets/Scripts/Timer.cs:29)”