Skip to main content
Most advice here is not unique to Unity 5, so the Unity tag suffices
Link
DMGregory
  • 136.3k
  • 22
  • 247
  • 373

Unity 5 - What is the proper way to handle data between scenes?

Tweeted twitter.com/StackGameDev/status/663147222813528068
Source Link

Unity 5 - What is the proper way to handle data between scenes?

I am developing my first 2D game in Unity and I have come across what seems an important question.

How do I handle data between scenes?

There seems to be different answers to this:

  • Someone mention using PlayerPrefs, while other people told me this should be used to store other things like screen brightness and so on.

  • Someone told me that the best way was to make sure to write everything into a savegame everytime that I changed scenes, and to make sure that when the new scene loads, get the info from the savegame again. This seemed to me wasteful in performance. Was I wrong?

  • The other solution, which is the one I have implemented so far is to have a global game object that isn't destroyed between scenes, handling all the data between scenes. So when the game starts, I load a Start Scene where this object is loaded. After this ends, it loads the first real game scene, usually a main menu.

This is my implementation:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class GameController : MonoBehaviour {

    // Make global
    public static GameController Instance {
        get;
        set;
    }

    void Awake () {
        DontDestroyOnLoad (transform.gameObject);
        Instance = this;
    }

    void Start() {
        //Load first game scene (probably main menu)
        Application.LoadLevel(2);
    }

    // Data persisted between scenes
    public int exp = 0;
    public int armor = 0;
    public int weapon = 0;
    //...
}

This object can be handled on my other classes like this:

private GameController gameController = GameController.Instance;

While this has worked so far, it presents me with one big problem: If I want to load directly a scene, let's say for instance the final level of the game, I can't load it directly, since that scene does not contain this global game object.

Am I handling this problem the wrong way? Are there better practices for this kind of challenge? I would love to hear your opinions, thoughts and suggestions on this issue.

Thanks