So I have any empty game object that I have my ScoreManager script attached to. Currently it is the only object in my game that I do not destroy between scenes:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour {
public static ScoreManager instance = null;
public Text scoreText;
public static float score = 0f;
private Text highScore;
// Use this for initialization
void Awake ()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
// Update is called once per frame
void Update ()
{
scoreText.text = score.ToString();
}
}
The problem is that after going to the game over scene and then back then back to the game I get an error for the code in the Update function “Object reference not set to an instance of the object”.
scoreText is a UI Text element attached to my Canvas in the hierarchy of the scene that contains my game. So I go from the title screen scene that doesn’t contain my ScoreManager object to my game where it is first introduced and it works, but after going from the game over scene back to the game scene I get this error.
Any suggestions on how to fix it? I kind of thought the scoreText variable would just reassign itself the same way it did when I first go from the title scene to the game scene. In the game scene I have the scoreText public and assigned it into the ScoreManager via the inspector like so:
If you destroy the thing it was referencing then the variable will become null. There’s no way for it to know when and where to go look for it again. You might be able to use this (http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnLevelWasLoaded.html) to go get the thing again after the level was loaded but I’m not sure if it’s still relevant with the SceneManager stuff that was introduced in 5.3
The other option is to DontDestroyOnLoad the text object as well.
I’ll give the Don’tDestroyOnLoad attempt for my Canvas.
I’m curious how one would go about reassigning my scoreText variable? I don’t know how you would do a GetComponent (or whatnot) to assign a UI Text element that is in the hierarchy to the Text variable (scoreText) in my script. I assume there has to be a way to do this.
I don’t have to have my UI Text parented to the Canvas? I can just parent it to my ScoreManager GameObject? Or are you talking about parenting the entire Canvas to my ScoreManager GameObject?
Sorry pretty new to working with UI. Was under the assumption that UI elements had to be parented to the Canvas.
They do. I meant just put your score manager script on the same object as your text. Or put it on your top-level canvas in order to DontDestroyOnLoad the whole thing.