- Home /
How to keep Text file going in different scenes?
I have made a stopwatch text file to calculate how fast the player can finish the game, but in order to do that I know that I need to use the DontDestroyOnLoad. But where do I put it? I have the script file so can someone tell me where to put it? Thank you very much..
[1]: /storage/temp/177042-capture.jpg
Answer by highpockets · Mar 05, 2021 at 07:08 AM
You can put it anywhere in your scene and the moment that it is called a persistent scene will be created and the game object will then be in that persistent scene which is like a scene layered on top of the scene you have running. When you load another scene, that persistent scene will continue to be there with the object which has the stop watch functionality. If classes in the new scene have to access that object/stopwatch class, you do as you would anytime you want to access any other class:
public class Stopwatch : MonoBehaviour
{
public Text stopwatchText;
private void Start()
{
DoNotDestroyOnLoad(gameObject);
}
}
Now access in in the next scene:
public class SomeClass : MonoBehaviour
{
private Text stopwatchText;
private void Start()
{
//Really slow, but no tag needed
stopwatchText = FindObjectOfType<Stopwatch>().stopwatchText;
//Alternatively you can access it by the tag which is a lot faster. The game object from the stopwatch would need this tag of course
stopwatchText = GameObject.FindWithTag(“StopwatchTagName”).GetComponent<Stopwatch>().stopwatchText;
}
}
Aww, Im afraid DontDestroyOnLoad only works on gameObjects and root components on gameObjects, I really appreciate your answer. Thank you!
Yes, that is correct. If you need to persist the stopwatch with a child of a game object, then you either need to use DontDestroyOnLoad(transform.root.gameObject);
to include the parent or remove the child and place it in at the root. Or you need to just persist the data instead with PlayerPrefs (un-secure) or in the file system (secure) to a new stopwatch in the next scene
Answer by b4guw1x · Mar 05, 2021 at 10:52 AM
If the text isn't that long, you can simply keep it with player prefs.
PlayerPrefs.SetString("PlayerTime","xxxxx");
When you want to acces it you can use
PlayerPrefs.GetString("PlayerTime");