How to pass data between scenes in Unity

后端 未结 5 1423
误落风尘
误落风尘 2020-11-22 08:30

How can I pass score value from one scene to another?

I\'ve tried the following:

Scene one:

void Start () {
    score = 0;
          


        
5条回答
  •  天命终不由人
    2020-11-22 08:49

    There are various way, but assuming that you have to pass just some basic data, you can create a singelton instance of a GameController and use that class to store the data.

    and, of course DontDestroyOnLoad is mandatory!

    public class GameControl : MonoBehaviour
    {
        //Static reference
    public static GameControl control;
    
    //Data to persist
    public float health;
    public float experience;
    
    void Awake()
    {
        //Let the gameobject persist over the scenes
        DontDestroyOnLoad(gameObject);
        //Check if the control instance is null
        if (control == null)
        {
            //This instance becomes the single instance available
            control = this;
        }
        //Otherwise check if the control instance is not this one
        else if (control != this)
        {
            //In case there is a different instance destroy this one.
            Destroy(gameObject);
        }
    }
    

    Here is the full tutorial with some other example.

提交回复
热议问题