- Home /
Displaying a Score in a Game Over Scene, taken from the MainGame Scene?
Hey guys, first time posting here! I'm currently doing an Infinite Runner and the score is currently based off how far the player has gotten from the starting point. Anyway, I'm using PlayerPrefs to grab this score and then display it in a different Scene (my Game Over Scene). It's also worth mentioning that this method DID work when I was basing score off of time survived, but now I'm getting an error saying 'Object reference not set to an instance of an object'. I think Unity is having trouble getting the info from the player. Anyway, here are the scripts I've been using.
Script that is creating then displaying the score in the main game (THIS WORKS).
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
public Transform player;
public Text distanceText;
public int score;
void onDisable () {
PlayerPrefs.SetInt ("Score", (int)score);
}
void Update () {
distanceText.text = Mathf.FloorToInt(player.position.x + 5f) + "m";
score = Mathf.FloorToInt(player.position.x + 5f);
}
}
This is the script (currently not working) for the game over screen, the problem is coming from the code within void Update.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GOverController : MonoBehaviour
{
int score = 0;
Text finalDistanceText;
void Awake ()
{
finalDistanceText = GetComponent <Text> ();
}
void Start ()
{
score = PlayerPrefs.GetInt ("Score");
}
void Update ()
{
finalDistanceText.text = "You Ran " + (int)score + "m";
}
}
Any insight from you guys would be awesome! Thanks!
Answer by taxvi · Feb 04, 2015 at 01:33 PM
yes the error is hitting on Update but that's because finalDistanceText does not get assigned properly in the Awake function.
stick this in after line 13:
if(finalDistanceText == null){
Debug.Log("finalDistanceText is null");
}
else{
Debug.Log("nope, Taxvi is a douchebag");
}
GetComponent (); will try to access a text component on the same transform. create a public Trasnsform variable, let's say myText and then go like myText.GetComponent (); then don't forget to drop the transform with the text component on this script in the inspector.
or not, there is a shorter way - just delete the line in the awake function, make the Text variable public and drop the object with the Text component on the script in the inspector.
Well, I learned how to Debug thanks to you and I was able to move stuff around and it works perfectly! Thanks brother!
If the answer is correct, you should mark the question answered by clicking the checkmark next to it.
Your answer
Follow this Question
Related Questions
Multiply float by int? 2 Answers
Show score on gameover screen? 1 Answer
Count scripting problem 1 Answer
Show Current Score on GAMEOVER Scene 0 Answers
Share score on facebook *Without facebook SDK* (ANDROID) 2 Answers