Home » What is the proper way to handle data between scenes?

What is the proper way to handle data between scenes?

Solutons:


Listed in this answer are the fundamental ways of handling this situation. However, most of these methods do not scale well to large projects. If you want something more scalable and are not afraid of getting your hands dirty, check out the answer by Lea Hayes about Dependency Injection frameworks.


1. A static class for holding data only

You can create a static class to hold data only. Since it is static, you don’t need to assign it to a GameObject (i.e. you don’t need to create an instance of it). You can simply access your data such as ClassName.Variable = data; etc.

Pros:

  • No instance or singleton is required.
  • You can access data from everywhere in your project.
  • No extra code to pass values between scenes.
  • All variables and data in a single database-like class make it easy to manage them.

Cons:

  • You cannot use a Coroutine inside a static class.
  • You will probably end up with a huge class if you don’t organize well.
  • Since static classes cannot be assigned to GameObjects, you can’t assign fields/variables inside the editor.

An Example:

public static class PlayerStats
{
    public static int Kills { get; set; }
    public static int Deaths { get; set; }
    public static int Assists { get; set; }
    public static float Points { get; set; }
}

2. DontDestroyOnLoad

If you need your script to be assigned to a GameObject or derive from MonoBehavior, then you can add DontDestroyOnLoad(gameObject); line to your class where it can be executed once (Placing it in Awake() is usually the way to go for this).

Pros:

  • All MonoBehaviour jobs (for example Coroutines) can be done safely.
  • You can assign fields inside the editor.

Cons:

  • You will probably need to adjust your scene depending on the script.
  • You will probably need to check which scene is loaded to determine what to do in Update() or other general functions/methods. For example, if you are doing something with UI in Update(), then you need to check if the correct scene is loaded to do the job. This may cause you to write lots of long if-else or switch-case statements.

3. PlayerPrefs

You can implement this if you also want your data to be stored even if the game gets closed.

Pros:

  • Easy to manage since Unity handles all background logic.
  • You can pass data not only between scenes but also between instances (game sessions).

Cons:

  • Uses file system.
  • Data can easily be changed from the prefs file.

4. Saving to a file

This is a bit overkill for storing values between scenes. If you don’t need encryption, I discourage you from this method.

Pros:

  • You are in control of data saved as opposed to PlayerPrefs.
  • You can pass data not only between scenes but also between instances (game sessions).
  • You can transfer the file (user-generated content concept relies on this).

Cons:

  • Slow.
  • Uses file system.
  • Possibility of reading/loading conflicts caused by stream interruption while saving.
  • Data can easily be changed from the file unless you implement encryption, which will make the code even slower.

5. Singleton pattern

Singleton pattern is a really controversial topic in object-oriented programming. Some suggest it, and some don’t. Research it yourself and make the appropriate call depending on your project’s needs and scale.

Pros:

  • Easy to both setup and use.
  • You can access data from everywhere in your project.
  • All variables and data in a single database-like class make it easy to manage them.

Cons:

  • Lots of boilerplate code whose only job is to maintain and secure the singleton instance.
  • There are strong arguments against the use of singleton pattern. Be cautious and make your research beforehand.
  • Possibility of data clash due to poor implementation.
  • Unity may have a difficulty handling singleton patterns1.

1: In the summary of OnDestroy method of Singleton Script provided in Unify Wiki, you can see the author describing ghost objects which bleed into the editor from runtime:

When Unity quits, it destroys objects in random order. In principle, a Singleton is only destroyed when the application quits. If any script calls Instance after it has been destroyed, it will create a buggy ghost object that will stay on the Editor scene even after stopping playing the Application. Really bad! So, this was made to be sure we’re not creating that buggy ghost object.

A slightly more advanced option is to perform dependency injection with a framework like Zenject.

This leaves you free to structure your application however you want; for instance,

public class PlayerProfile
{
    public string Nick { get; set; }
    public int WinCount { get; set; }
}

You can then bind the type to the IoC (inversion of control) container. With Zenject this action is performed inside a MonoInstaller or a ScriptableInstaller:

public class GameInstaller : MonoInstaller
{
    public override void InstallBindings()
    {
        this.Container.Bind<PlayerProfile>()
            .ToSelf()
            .AsSingle();
    }
}

The singleton instance of PlayerProfile is then injected into other classes that are instantiated via Zenject. Ideally through constructor injection but property and field injection is also possible by annotating them with Zenject’s Inject attribute.

The latter attribute technique is used to automatically inject the game objects of your scene since Unity instantiates these objects for you:

public class WinDetector : MonoBehaviour
{
    [Inject]
    private PlayerProfile playerProfile = null;


    private void OnCollisionEnter(Collision collision)
    {
        this.playerProfile.WinCount += 1;
        // other stuff...
    }
}

For whatever reason you might also want to bind an implementation by interface rather than by the implementation type. (Disclaimer, the following isn’t supposed to be an amazing example; I doubt you’d want Save/Load methods in this particular location… but this just shows an example of how implementations could vary in behaviour).

public interface IPlayerProfile
{
    string Nick { get; set; }
    int WinCount { get; set; }

    void Save();
    void Load();
}

[JsonObject]
public class PlayerProfile_Json : IPlayerProfile
{
    [JsonProperty]
    public string Nick { get; set; }
    [JsonProperty]
    public int WinCount { get; set; }


    public void Save()
    {
        ...
    }

    public void Load()
    {
        ...
    }
}

[ProtoContract]
public class PlayerProfile_Protobuf : IPlayerProfile
{
    [ProtoMember(1)]
    public string Nick { get; set; }
    [ProtoMember(2)]
    public int WinCount { get; set; }


    public void Save()
    {
        ...
    }

    public void Load()
    {
        ...
    }
}

Which can then be bound to the IoC container in a similar way as before:

public class GameInstaller : MonoInstaller
{
    // The following field can be adjusted using the inspector of the
    // installer component (in this case) or asset (in the case of using
    // a ScriptableInstaller).
    [SerializeField]
    private PlayerProfileFormat playerProfileFormat = PlayerProfileFormat.Json;


    public override void InstallBindings()
    {
        switch (playerProfileFormat) {
            case PlayerProfileFormat.Json:
                this.Container.Bind<IPlayerProfile>()
                    .To<PlayerProfile_Json>()
                    .AsSingle();
                break;

            case PlayerProfileFormat.Protobuf:
                this.Container.Bind<IPlayerProfile>()
                    .To<PlayerProfile_Protobuf>()
                    .AsSingle();
                break;

            default:
                throw new InvalidOperationException("Unexpected player profile format.");
        }
    }


    public enum PlayerProfileFormat
    {
        Json,
        Protobuf,
    }
}

You’re doing things in a good way. It’s the way I do it, and clearly the way many people do it because this autoloader script (you can set a scene to automatically load first whenever you hit Play) exists: http://wiki.unity3d.com/index.php/SceneAutoLoader

Both of the first two options are also things your game may need for saving the game between sessions, but those are wrong tools for this problem.

Related Solutions

Extract file from docker image?

You can extract files from an image with the following commands: docker create $image # returns container ID docker cp $container_id:$source_path $destination_path docker rm $container_id According to the docker create documentation, this doesn't run the...

Transfer files using scp: permission denied

Your commands are trying to put the new Document to the root (/) of your machine. What you want to do is to transfer them to your home directory (since you have no permissions to write to /). If path to your home is something like /home/erez try the following:...

What’s the purpose of DH Parameters?

What exactly is the purpose of these DH Parameters? These parameters define how OpenSSL performs the Diffie-Hellman (DH) key-exchange. As you stated correctly they include a field prime p and a generator g. The purpose of the availability to customize these...

How to rsync multiple source folders

You can pass multiple source arguments. rsync -a /etc/fstab /home/user/download bkp This creates bkp/fstab and bkp/download, like the separate commands you gave. It may be desirable to preserve the source structure instead. To do this, use / as the source and...

Benefits of Structured Logging vs basic logging

There are two fundamental advances with the structured approach that can't be emulated using text logs without (sometimes extreme levels of) additional effort. Event Types When you write two events with log4net like: log.Debug("Disk quota {0} exceeded by user...

Interfaces vs Types in TypeScript

2019 Update The current answers and the official documentation are outdated. And for those new to TypeScript, the terminology used isn't clear without examples. Below is a list of up-to-date differences. 1. Objects / Functions Both can be used to describe the...

Get total as you type with added column (append) using jQuery

One issue if that the newly-added column id's are missing the id number. If you look at the id, it only shows "price-", when it should probably be "price-2-1", since the original ones are "price-1", and the original ones should probably be something like...

Determining if a file is a hard link or symbolic link?

Jim's answer explains how to test for a symlink: by using test's -L test. But testing for a "hard link" is, well, strictly speaking not what you want. Hard links work because of how Unix handles files: each file is represented by a single inode. Then a single...

How to restrict a Google search to results of a specific language?

You can do that using the advanced search options: http://www.googleguide.com/sharpening_queries.html I also found this, which might work for you: http://www.searchenginejournal.com/how-to-see-google-search-results-for-other-locations/25203/ Just wanted to add...

Random map generation

Among the many other related questions on the site, there's an often linked article for map generation: Polygonal Map Generation for Games you can glean some good strategies from that article, but it can't really be used as is. While not a tutorial, there's an...

How to prettyprint a JSON file?

The json module already implements some basic pretty printing in the dump and dumps functions, with the indent parameter that specifies how many spaces to indent by: >>> import json >>> >>> your_json = '["foo", {"bar":["baz", null,...

How can I avoid the battery charging when connected via USB?

I have an Android 4.0.3 phone without root access so can't test any of this but let me point you to /sys/class/power_supply/battery/ which gives some info/control over charging issues. In particular there is charging_enabled which gives the current state (0 not...

How to transform given dataset in python? [closed]

From your expected result, it appears that each "group" is based on contiguous id values. For this, you can use the compare-cumsum-groupby pattern, and then use agg to get the min and max values. # Sample data. df = pd.DataFrame( {'id': [1, 2, 2, 2, 2, 2, 1, 1,...

Output of the following C++ Program [closed]

It works exactly like this non-recursive translation: int func_0() { return 2; } int func_1() { return 3; } int func_2() { return func_1() + func_0(); } // Returns 3 + 2 = 5 int func_3() { return func_2() + func_1(); } // Returns 5 + 3 = 8 int func_4() { return...

Making a circle out of . (periods) [closed]

Here's the maths and even an example program in C: http://pixwiki.bafsoft.com/mags/5/articles/circle/sincos.htm (link no longer exists). And position: absolute, left and top will let you draw: http://www.w3.org/TR/CSS2/visuren.html#choose-position Any further...

Should I use a code converter (Python to C++)?

Generally it's an awful way to write code, and does not guarantee that it will be any faster. Things which are simple and fast in one language can be complex and slow in another. You're better off either learning how to write fast Python code or learning C++...

tkinter: cannot concatenate ‘str’ and ‘float’ objects

This one line is more than enough to cause the problem: text="რეგულარი >> "+2.23+ 'GEL' 2.23 is a floating-point value; 'GEL' is a string. What does it mean to add an arithmetic value and a string of letters? If you want the string label 'რეგულარი...