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…
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;
}
}
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");