unity switch to scene and transfer data code example
Example: unity switch to scene and transfer data
using UnityEngine;
/// Manages data for persistance between levels.
public class DataManager : MonoBehaviour
{
/// Static reference to the instance of our DataManager
public static DataManager instance;
/// The player's current score.
public int score;
/// The player's remaining health.
public int health;
/// The player's remaining lives.
public int lives;
/// Awake is called when the script instance is being loaded.
void Awake()
{
// If the instance reference has not been set, yet,
if (instance == null)
{
// Set this instance as the instance reference.
instance = this;
}
else if(instance != this)
{
// If the instance reference has already been set, and this is not the
// the instance reference, destroy this game object.
Destroy(gameObject);
}
// Do not destroy this object, when we load a new scene.
DontDestroyOnLoad(gameObject);
}
}