- Home /
Canvas Button persistence
Hi all,
i have buttons and other UI elements. I have onClick event to Call Load() Save() Delete() funktions. Now if i load another Scene abd go back to the first Scene the connection to the gameobject with the funtions inside are gone. How could i get the connections back to the buttons?
Same to text elements. I tried to find the gameobject in the awake() but after reloading the scene the connection again is missing.
The script for text example.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MoneyScript : MonoBehaviour {
public static MoneyScript moneyS;
public int coins = 0;
public Text coinText;
private Text CT;
void Awake()//happends before start
{
//make sure the gameobject is a prefab
if(moneyS == null)//if moneyS does not exist
{
DontDestroyOnLoad (gameObject);//make a gameobject persistent
moneyS = this;//make moneyS this script
}
else if(moneyS != this)//if it is not this
{
Destroy(gameObject);//destroy it
}
}
void Start()
{
// I want to get the textfield here ....
CT = GameObject.Find ("coinText").GetComponent<Text> ();
if(CT != null)
coinText = CT;
}
public void addCoins(int money)
{
coins += money;
coinText.text = coins.ToString ();
}
}
I found out, that canvas buttons shouldn't have a reference to persistent gameobjects, then they work.
But how about text? I need that to show the player how much money they have.
Because of "DontDestroyOnLoad", the method Start won't be called when loading a new scene. Did you tried "OnLevelWasLoaded" method ?
void OnLevelWasLoaded()
{
CT = GameObject.Find ("coinText").GetComponent<Text> ();
if(CT != null)
coinText = CT;
}
You should really avoid GameObject.Find, prefer to use GameObject.FindWithTag
Side question... why do you have coinText as public (and set in the inspector) but find it using a private variable CT and then overwriting what was put in using coinText. But you never check if coinText was set in the inspector before just overwriting it.
If you do set it in the inspector and just want to make sure it is set properly, you can check the value of coinText and then that will save the cost of Find() if it's not needed.
Thanks alot, works like a charm. I didn't knew there is such a function.
Narv: I tried to fix my problem, so i tried to find the gameobject and get it back to it's initial state. Basicly i could make it private and search the object in Start() and OnLevelWasLoaded().
But since i have a persistent gameobject i could't just get it back because of $$anonymous$$outon's answer.
Your answer
Follow this Question
Related Questions
Missing canvas elements on Build & Run. 2 Answers
Unity UI Text Blurriness 0 Answers