Friday, July 8, 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?


A really perfect 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’ll be able to guarantee it’s instantly accessible and persists between scenes.

An alternative choice you’ve gotten is to make use of the PlayerPrefs class. PlayerPrefs is designed to help you save information between play periods, however it should nonetheless function a method 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 identical time. By offering such performance, we will safely create a static self-reference, to entry the category from anyplace. This implies which you can immediately 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 known as 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 recreation object.
            Destroy(gameObject);
        }

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

You may see the singleton in motion, under. Word 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 in school to handle primary persistent information known as PlayerPrefs. Any information dedicated to the PlayerPrefs file will persist throughout recreation periods, 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 periods.</abstract>
public class SaveManager : MonoBehaviour 
{
    /// <abstract>The participant's title.</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 document of the important thing for saving and loading playerName.</abstract>
    personal static string playerNameKey = "PLAYER_NAME";
    /// <abstract>Static document of the important thing for saving and loading playerScore.</abstract>
    personal static string playerScoreKey = "PLAYER_SCORE";
    /// <abstract>Static document 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 present has a worth registered to the playerNameKey, 
        if (PlayerPrefs.HasKey(playerNameKey))
        {
            // load playerName from the PlayerPrefs file.
            playerName = PlayerPrefs.GetString(playerNameKey);
        }

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

        // If the PlayerPrefs file at present has a worth 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();
    }
}

Word that I take further precautions, when dealing with the PlayerPrefs file:

  • I’ve saved every key as a personal static string. This enables me to ensure I’m at all times utilizing the precise key, and it signifies that if I’ve to alter the important thing for any cause, I don’t want to make sure I alter 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 periods. PlayerPrefs will save to the disk throughout a traditional software shut, however it might not naturally name in case your recreation crashes.
  • I really examine that every key exists within the PlayerPrefs, earlier than I try and retrieve a worth related to it. This would possibly seem to be pointless double-checking, however it’s a good observe to have.
  • I’ve a Delete technique that instantly wipes the PlayerPrefs file. If you don’t intend to incorporate information persistence throughout play periods, you would possibly think about calling this technique on Awake. By clearing the PlayerPrefs file at first of every recreation, you make sure that any information that did persist from the earlier session isn’t mistakenly dealt with as information from the present session.

You may see PlayerPrefs in motion, under. Word that after I click on “Save Knowledge”, I’m immediately calling the Save technique, and after I click on “Load Knowledge”, I’m immediately calling the Load technique. Your individual implementation will seemingly fluctuate, however it demonstrates the fundamentals.

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


As a last be aware, I ought to level out which you can broaden upon the essential PlayerPrefs, to retailer extra helpful sorts. JPTheK9 gives an excellent reply to an analogous query, by which they supply a script for serialising arrays into string type, to be saved in a PlayerPrefs file. In addition they level us to the Unify Group Wiki, the place a consumer has uploaded a extra expansive PlayerPrefsX script to permit assist for a higher number of sorts, reminiscent of 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