- Home /
Text.text doesnt work after scene change
This problem is just weird... I have a "Shop" scene with a Text displaying the user's current in-game currency.
The Text is assigned to "txt_money" through the unity editor and works perfectly when you start the game in the Shop scene. But when i change scene and come back to the Shop i get the following error:
MissingReferenceException: The object of type 'Text' has been destroyed but you are still trying to access it.
Further I inserted some debug.log's to see if the object exists when changing scenes and it EXISTS IN UPDATE, but DOES NOT EXIST IN the "Purchase()" method.
:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Shop : MonoBehaviour
{
public int money;
public Text txt_money;
private void Update() {
// txt_money exists here...
Debug.Log(txt_money); // Always prints "Text (UnityEngine.UI.Text)"
}
public void Purchase(int ammount) {
// txt_money does not exist here ?
Debug.Log(txt_money); // Prints "null"
money += ammount;
txt_money.text = money.ToString();
}
}
:
Im not sure what to try to fix it, any suggestions?
Answer by RewForeN · Mar 19, 2019 at 10:40 AM
Still dont know why the original code didnt work but found a work around:
public class Shop : MonoBehaviour
{
public static Shop Instance {set; get;}
private void Awake() {
Instance = this;
}
}
:
Then where "Purchase()" is called:
Shop.Instance.Purchase(ammount);
Answer by dargonknight · Mar 19, 2019 at 09:56 AM
@RewForeN where is the purchase function called? maybe it's called before the object initialize properly? start by removing it from everywhere and having it on a button, click that button after few seconds if it's still an not valid maybe assign in the beginning of the function and check what happens next in the editor after following those steps and dealing with the result let me know if things work out.
It is called from another script that processes purchases through google play games
@RewForeN that's why it didn't work the call was happening before everything else, the process i described is 1 of the easiest when you want to debug such issues, keep it in $$anonymous$$d whenever ur facing such issues
Your answer
Follow this Question
Related Questions
UI Scene ending with Text 1 Answer
Previous UI text sticks around even after reloading scene using SceneManager.LoadScene(scene.name); 0 Answers
Get Text from an Input Field on one scene and use it as a text on another scene Unity c# 0 Answers
How do I switch scenes by obtain a children ui canvas text 0 Answers