- Home /
Question by
KenzyLamar · Oct 07, 2018 at 10:48 AM ·
collectible
Add up coins in the StartMenu
Hello everyone i would like to ask how can coins collected in the game play scene add up in the main menu which is a separate scene.
Comment
Answer by LeonardNS · Oct 07, 2018 at 12:44 PM
Method one - DontDestroyOnLoad
You can place a script that saves this information on an object that you mark with DontDestroyOnLoad.
using UnityEngine;
using UnityEngine.SceneManagement;
public class DataContainer : MonoBehaviour {
public int numberOfClicks = 0;
private void Start() {
DontDestroyOnLoad(gameObject);
}
private void Update() {
if (Input.GetMouseButtonDown(0)) {
numberOfClicks++;
}
if (Input.GetMouseButtonDown(1)) {
SceneManager.LoadScene("Test_2");
}
}
}
This script will count number of times you click the mouse, then when you change scene, it will not be destroyed, and gameObjects in the new scene can access it normally with stuff like FindWithTag.
Method two - Static fields
You can also save information in static fields on a class.
using UnityEngine;
using UnityEngine.SceneManagement;
public class DataContainer : MonoBehaviour {
public static int numberOfClicks = 0;
private void Start() {
Debug.Log("Previous DataContainers have already clicked up to " + numberOfClicks);
}
private void Update() {
if (Input.GetMouseButtonDown(0)) {
numberOfClicks++;
Debug.Log(numberOfClicks);
}
if (Input.GetMouseButtonDown(1)) {
SceneManager.LoadScene("Test_2");
}
}
}
If you put one of these in each scene, they will continue where the last one left off because they all access the same static field - numberOfClicks.