Tuesday, August 2, 2022
HomeGame Developmentunity - What's the correct method to deal with information between scenes?

unity – What’s the correct method to deal with information between scenes?


An excellent method to retailer variables between scenes is thru a singleton supervisor class. By creating a category to retailer persistent information, and setting that class to DoNotDestroyOnLoad(), you possibly can guarantee it’s instantly accessible and persists between scenes.

Another choice you will have is to make use of the PlayerPrefs class. PlayerPrefs is designed to permit you to save information between play classes, however it is going to nonetheless function a way to save lots of information between scenes.

Utilizing a singleton class and DoNotDestroyOnLoad()

The next script creates a persistent singleton class. A singleton class is a category that’s designed to solely run a single occasion on the similar time. By offering such performance, we are able to safely create a static self-reference, to entry the category from wherever. This implies that you may instantly entry the category with DataManager.occasion, together with any public variables inside the category.

utilizing UnityEngine;

/// <abstract>Manages information for persistance between ranges.</abstract>
public class DataManager : MonoBehaviour 
{
    /// <abstract>Static reference to the occasion of our DataManager</abstract>
    public static DataManager occasion;

    /// <abstract>The participant's present rating.</abstract>
    public int rating;
    /// <abstract>The participant's remaining well being.</abstract>
    public int well being;
    /// <abstract>The participant's remaining lives.</abstract>
    public int lives;

    /// <abstract>Awake is named when the script occasion is being loaded.</abstract>
    void Awake()
    {
        // If the occasion reference has not been set, but, 
        if (occasion == null)
        {
            // Set this occasion because the occasion reference.
            occasion = this;
        }
        else if(occasion != this)
        {
            // If the occasion reference has already been set, and this isn't the
            // the occasion reference, destroy this sport object.
            Destroy(gameObject);
        }

        // Don't destroy this object, after we load a brand new scene.
        DontDestroyOnLoad(gameObject);
    }
}

You’ll be able to see the singleton in motion, under. Be aware that as quickly as I run the preliminary scene, the DataManager object strikes from the scene-specific heading to the “DontDestroyOnLoad” heading, on the hierarchy view.

A screen recording of multiple scenes being loaded, while the DataManager persists under the "DoNotDestroyOnLoad" heading.

Utilizing the PlayerPrefs class

Unity has a constructed at school to handle primary persistent information referred to as PlayerPrefs. Any information dedicated to the PlayerPrefs file will persist throughout sport classes, so naturally, it’s able to persisting information throughout scenes.

The PlayerPrefs file can retailer variables of sorts string, int and float. After we insert values into the PlayerPrefs file, we offer an extra string as the important thing. We use the identical key to later retrieve our values from the PlayerPref file.

utilizing UnityEngine;

/// <abstract>Manages information for persistance between play classes.</abstract>
public class SaveManager : MonoBehaviour 
{
    /// <abstract>The participant's identify.</abstract>
    public string playerName = "";
    /// <abstract>The participant's rating.</abstract>
    public int playerScore = 0;
    /// <abstract>The participant's well being worth.</abstract>
    public float playerHealth = 0f;

    /// <abstract>Static report of the important thing for saving and loading playerName.</abstract>
    personal static string playerNameKey = "PLAYER_NAME";
    /// <abstract>Static report of the important thing for saving and loading playerScore.</abstract>
    personal static string playerScoreKey = "PLAYER_SCORE";
    /// <abstract>Static report of the important thing for saving and loading playerHealth.</abstract>
    personal static string playerHealthKey = "PLAYER_HEALTH";

    /// <abstract>Saves playerName, playerScore and 
    /// playerHealth to the PlayerPrefs file.</abstract>
    public void Save()
    {
        // Set the values to the PlayerPrefs file utilizing their corresponding keys.
        PlayerPrefs.SetString(playerNameKey, playerName);
        PlayerPrefs.SetInt(playerScoreKey, playerScore);
        PlayerPrefs.SetFloat(playerHealthKey, playerHealth);

        // Manually save the PlayerPrefs file to disk, in case we expertise a crash
        PlayerPrefs.Save();
    }

    /// <abstract>Saves playerName, playerScore and playerHealth 
    // from the PlayerPrefs file.</abstract>
    public void Load()
    {
        // If the PlayerPrefs file at the moment has a price registered to the playerNameKey, 
        if (PlayerPrefs.HasKey(playerNameKey))
        {
            // load playerName from the PlayerPrefs file.
            playerName = PlayerPrefs.GetString(playerNameKey);
        }

        // If the PlayerPrefs file at the moment has a price registered to the playerScoreKey, 
        if (PlayerPrefs.HasKey(playerScoreKey))
        {
            // load playerScore from the PlayerPrefs file.
            playerScore = PlayerPrefs.GetInt(playerScoreKey);
        }

        // If the PlayerPrefs file at the moment has a price registered to the playerHealthKey,
        if (PlayerPrefs.HasKey(playerHealthKey))
        {
            // load playerHealth from the PlayerPrefs file.
            playerHealth = PlayerPrefs.GetFloat(playerHealthKey);
        }
    }

    /// <abstract>Deletes all values from the PlayerPrefs file.</abstract>
    public void Delete()
    {
        // Delete all values from the PlayerPrefs file.
        PlayerPrefs.DeleteAll();
    }
}

Be aware that I take extra precautions, when dealing with the PlayerPrefs file:

  • I’ve saved every key as a personal static string. This permits me to ensure I’m at all times utilizing the fitting key, and it signifies that if I’ve to alter the important thing for any purpose, I don’t want to make sure I modify all references to it.
  • I save the PlayerPrefs file to the disk after writing to it. This most likely will not make a distinction, if you don’t implement information persistence throughout play classes. PlayerPrefs will save to the disk throughout a traditional utility shut, however it could not naturally name in case your sport crashes.
  • I really verify that every key exists within the PlayerPrefs, earlier than I try and retrieve a price related to it. This may appear to be pointless double-checking, however it’s a good follow to have.
  • I’ve a Delete technique that instantly wipes the PlayerPrefs file. If you don’t intend to incorporate information persistence throughout play classes, you may think about calling this technique on Awake. By clearing the PlayerPrefs file at the beginning of every sport, you make sure that any information that did persist from the earlier session just isn’t mistakenly dealt with as information from the present session.

You’ll be able to see PlayerPrefs in motion, under. Be aware that once I click on “Save Knowledge”, I’m instantly calling the Save technique, and once I click on “Load Knowledge”, I’m instantly calling the Load technique. Your individual implementation will possible fluctuate, nevertheless it demonstrates the fundamentals.

A screen recording of data persisting passed being overwritten from the inspector, through the Save() and Load() functions.


As a ultimate notice, I ought to level out that you may develop upon the essential PlayerPrefs, to retailer extra helpful sorts. JPTheK9 supplies an excellent reply to an analogous query, during which they supply a script for serialising arrays into string type, to be saved in a PlayerPrefs file. Additionally they level us to the Unify Neighborhood Wiki, the place a consumer has uploaded a extra expansive PlayerPrefsX script to permit assist for a better number of sorts, comparable to vectors and arrays.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments