Tuesday, July 19, 2022
HomeWeb DevelopmentWhy it is best to (or shouldn’t) save information with Unity’s PlayerPrefs

Why it is best to (or shouldn’t) save information with Unity’s PlayerPrefs


Whether or not you’re comparatively new to creating in Unity otherwise you’ve bought a number of tasks below your belt, you’ve almost certainly realized how helpful it could be for gamers to avoid wasting information.

In the event you’re like most of us, your first intuition may be to do a fast search on methods to save participant information in Unity. From this search, it’s possible you’ll be shocked that there are fairly a number of totally different solutions, all various in complexity.

The best resolution is a Unity class referred to as PlayerPrefs. On this article, we’ll go over what PlayerPrefs is, how, when, and when to not use it. We’ll additionally focus on affordable options to utilizing PlayerPrefs.

Utilizing PlayerPrefs in Unity

With PlayerPrefs, you’ll be able to have an easy-to-use interface that lets you begin persisting some information!

Let’s say you’ve made a easy sport with some variety of ranges. You’ve determined you wish to save the extent your participant is on after they give up the sport in order that the right degree hundreds again up after they begin once more.

Nicely, this appears to be like fairly simple in PlayerPrefs. All you might want to do to avoid wasting the extent is the next:

<pre>
    // currentLevel is an integer variable representing the extent the participant is on
PlayerPrefs.SetInt("Degree", currentLevel);
PlayerPrefs.Save();
</pre>

If you’re able to load, getting the saved worth is simply as simple:

<pre>
// You may set a default return worth if you have not saved a "Degree" but with the second parameter
    currentLevel = PlayerPrefs.GetInt("Degree", 0);
</pre>

This definitely appears to be about as simple because it will get, so it’s time to avoid wasting information, proper?

Nicely, kind of. The quick reply is that saving a sport state like that is usually a nasty thought.

The longer reply is that saving and loading information in Unity is definitely a really deep matter with out a clear greatest resolution.

Drawbacks to utilizing PlayerPrefs

Let’s begin by taking a better take a look at PlayerPrefs to see if it’s one thing we wish to use to avoid wasting our sport information. A great first step on this course of is to examine the docs for PlayerPrefs. Immediately, some issues ought to increase some eyebrows.

Technique of saving information

Initially, PlayerPrefs saves information on a per-application foundation. Which means if you wish to have multiple save file in your software, you might want to get inventive. For instance, you can select to append a save file ID to every entry in PlayerPrefs and solely load and save based mostly on that ID.

After all, you then additionally have to discover a technique to save an inventory of participant IDs, which brings us to the subsequent challenge with utilizing PlayerPrefs: you’ll be able to solely save information as a string, float, or integer.

Particular information varieties

You in all probability know that there are extra information varieties than simply string, float, and integer. You may in all probability envision a state of affairs the place you’d wish to use an information kind aside from these three. This must be an enormous pink flag for us when attempting to determine if this class is appropriate for saving sport information.

If we have to assemble some kind of sophisticated string parsing system to imitate the conduct of a easy listing, we may be barking up the incorrect tree.

Location of saved information

One other necessary tidbit we are able to extract from the docs is the place the situation of the info from PlayerPrefs is definitely saved. This can be one thing you haven’t given a lot thought to when you’re comparatively new to programming, however saved information is simply information that exists someplace in a file.

That file may be on a unique pc throughout the nation within the case of a web based software, or it would simply be in a sub folder referred to as information. The file might be structured like a database or might be a easy textual content file, it simply is dependent upon what the appliance builders felt like doing.

On this case, if we’re on a Home windows pc, we are able to see from the docs that PlayerPrefs entries are saved to the registry. This must be one other pink flag when contemplating saving sport information with PlayerPrefs. The registry is actually not used for that kind of factor and primarily saves system and software configuration information.

With all these flags and eyebrows popping up, it’s fairly pure to surprise what precisely PlayerPrefs is used for if not for saving participant progress information. Nicely, the primary clue (and level of confusion) comes from the title.

When to make use of Unity’s PlayerPrefs

In the event you thought that the title “PlayerPrefs” alludes to the preferences of the participant, you’re definitely not alone, however you might be additionally incorrect.

The “Participant” in “PlayerPrefs” really refers back to the Unity Participant, the title of the standalone Unity Engine software that will get constructed whenever you flip your sport into an software of its personal. You could have come throughout this naming conference when altering settings in your mission in Unity, because the runtime choices are below Participant Settings.

With this in thoughts, we are able to begin to discover some affordable use circumstances for PlayerPrefs.

Most tasks made with Unity will in all probability wish to launch with a selected decision or high quality degree. Whereas we might select to avoid wasting settings associated to those issues with the remainder of our sport information, additionally it is affordable to imagine {that a} snug decision isn’t actually related for every save, however is extra related to the appliance with respect to the pc it runs on.

On this case, saving decision with PlayerPrefs might make good sense. With every new save file your customers create, the appliance decision stays at no matter they initially set. That is extra optimum than defaulting to a worth that won’t even work on every person’s machine every time they begin a brand new save.

The PlayerPrefs class is just not a perfect technique to save sport or per person information for a Unity mission. The information varieties are very restrictive and information can’t be simply separated from every person. Nevertheless, it is a superb interface for saving configuration and settings info related to every particular software, akin to decision, high quality degree, default audio machine, and extra.

So if we aren’t going to avoid wasting our sport information utilizing PlayerPrefs, what are we going to do? Step one is to actually take into consideration the specifics of your software and the way person information goes to be dealt with.

For instance, it’s a good suggestion to consider what would occur if the person might entry the info saved by your software. Realistically, any native saving system (together with utilizing PlayerPrefs) will result in this risk.

If the reply is that it could be catastrophically dangerous, you then in all probability already know that you might want to be saving person information off-site on a separate server (as is the case with virtually all on-line purposes). In case you are making an offline software, nevertheless, the solutions can fluctuate fairly wildly.

Within the case of a sport, having your customers entry their very own save information might be not the worst factor, however it might result in manipulation of the sport state and even unintentional corruption of their progress. There isn’t loads you are able to do concerning the latter, since it doesn’t matter what format your information is saved in, it should doubtless at all times be doable to discover a technique to randomly take away a piece of it. For the previous, there are a few choices that vary from not worrying about it to encrypting your save information to make it harder, although not inconceivable, to govern.

Storing information with out PlayerPrefs

To maintain issues easy, let’s deal with saving information for an area software. In essence, all we have to do to avoid wasting participant information is write info to a file. In Unity, the best method to do that is with a StreamWriter and JsonUtility.

StreamWriter will allow us to really write information to a file, and JsonUtility will deal with changing the info we wish to save into JavaScript Object Notation (JSON).

Whereas we aren’t really utilizing any JavaScript, JSON has change into one of many requirements for transmitting information attributable to its comfort for internet purposes. It is extremely simply learn by people and maps very merely to JavaScript objects.

For our functions, we are going to let Unity deal with the precise translation to and from JSON by way of JsonUtility. JsonUtility is kind of a blessing and a curse, since it is vitally quick however has a number of limitations.

Earlier than implementing this in your tasks, I encourage you to learn the docs. It’s very helpful to know a number of the limitations of JsonUtility earlier than going all-in for a mission.

Let’s check out an instance earlier than the weeds get too thick.

<pre>
utilizing System.IO;
utilizing UnityEngine;

public class DataManager
{
    personal Knowledge gameData;
    personal static string dataFilePath = Path.Mix(Utility.persistentDataPath, "GameData.json");

    public DataManager(int degree = 0)
    {
        gameData = new Knowledge();
        gameData.degree = degree;
    }

    // Right here we set our degree with some kind of GameManager
    public void SetLevel(int degree)
    {
        if (gameData == null)
        {
            gameData = new Knowledge();
        }

        gameData.degree = degree;
    }

    // The tactic to return the loaded sport information when wanted
    public Knowledge GetGameData()
    {
        return gameData;
    }

    public void Save()
    {
        // This creates a brand new StreamWriter to put in writing to a selected file path
        utilizing (StreamWriter author = new StreamWriter(dataFilePath))
        {
            // This can convert our Knowledge object right into a string of JSON
            string dataToWrite = JsonUtility.ToJson(gameData);

            // That is the place we really write to the file
            author.Write(dataToWrite);
        }
    }

    public void Load()
    {
        // This creates a StreamReader, which permits us to learn the info from the required file path
        utilizing (StreamReader reader = new StreamReader(dataFilePath))
        {
            // We learn within the file as a string
            string dataToLoad = reader.ReadToEnd();

            // Right here we convert the JSON formatted string into an precise Object in reminiscence
            gameData = JsonUtility.FromJson<Knowledge>(dataToLoad);
        }
    }

    [System.Serializable]
    public class Knowledge
    {
        // The precise information we wish to save goes right here, for this instance we'll solely use an integer to symbolize the extent
        public int degree = 0;
    }
}
</pre>

This instance must be sufficient to start out saving and loading information in your native Unity tasks. Internet-based tasks are advanced sufficient that we gained’t be masking information administration practices for them right here.

Clearly, there is a little more overhead right here than with the PlayerPrefs class. Nevertheless, after getting a easy save and cargo arrange, it’s virtually as simple to make use of in observe. One factor to notice right here is that the info saved in GameData.json goes to be simply readable and, due to this fact, modifiable.

Which means in its present state, it wouldn’t be too troublesome for an finish person to change their save information. To make this harder, we would want to look into totally different strategies of encryption for our information.

Encrypting save information is a bit past the scope of this text, however there are lots of thorough assets obtainable on the subject in case you are so inclined to look. For now, as a substitute for PlayerPrefs for native, nonsensitive information, the straightforward file operations outlined listed below are a good way to get began saving sport information.

Instance of implementing PlayerPrefs

So what about PlayerPrefs? Because it’s a wonderful system for saving computer-specific info, we are able to modify our instance to additionally avoid wasting settings information in a method that doesn’t intervene with our file operations and can persist throughout customers on the identical pc.

<pre>
utilizing System.IO;
utilizing UnityEngine;

public class DataManager
{
    personal Knowledge gameData;
    personal SettingsData settingsData;
    personal static string dataFilePath = Path.Mix(Utility.persistentDataPath, "GameData.json");

    public DataManager(int degree = 0)
    {
        gameData = new Knowledge();
        gameData.degree = degree;

        settingsData = new SettingsData(0, 1920, 1080);
    }

    // Right here we set our degree with some kind of GameManager
    public void SetLevel(int degree)
    {
        if (gameData == null)
        {
            gameData = new Knowledge();
        }

        gameData.degree = degree;
    }

    // The tactic to return the loaded sport information when wanted
    public Knowledge GetGameData()
    {
        return gameData;
    }

    // This can be utilized once we change settings values
    public void SetSettings(int high quality, int horizontalResolution, int verticalResolution)
    {
        settingsData = new SettingsData(high quality, horizontalResolution, verticalResolution);
    }

    public void SaveSettings()
    {
        PlayerPrefs.SetInt("QualityLevel", settingsData.qualityLevel);
        PlayerPrefs.SetInt("HorizontalResolution", settingsData.horizontalResolution);
        PlayerPrefs.SetInt("VerticalResolution", settingsData.verticalResolution);
        PlayerPrefs.Save();
    }

    public void LoadSettings()
    {
        // We are able to get a default worth if there is no such thing as a settings info, which is what the second parameter
        // within the PlayerPrefs.GetInt(p1, p2) is for
        settingsData = new SettingsData(
                            PlayerPrefs.GetInt("QualityLevel", 0),
                            PlayerPrefs.GetInt("HorizontalResolution", 1920),
                            PlayerPrefs.GetInt("VerticalResolution", 1080)
                        );
    }

    public void Save()
    {
        // This creates a brand new StreamWriter to put in writing to a selected file path
        utilizing (StreamWriter author = new StreamWriter(dataFilePath))
        {
            // This can convert our Knowledge object right into a string of JSON
            string dataToWrite = JsonUtility.ToJson(gameData);

            // That is the place we really write to the file
            author.Write(dataToWrite);
        }

        // This does not have to be coupled to the Save operate, and possibly should not be,
        // however for demonstration functions we'll put this right here
        SaveSettings();
    }

    public void Load()
    {
        // This creates a StreamReader, which permits us to learn the info from the required file path
        utilizing (StreamReader reader = new StreamReader(dataFilePath))
        {
            // We learn within the file as a string
            string dataToLoad = reader.ReadToEnd();

            // Right here we convert the JSON formatted string into an precise Object in reminiscence
            gameData = JsonUtility.FromJson<Knowledge>(dataToLoad);
        }

        LoadSettings();
    }

    public class SettingsData
    {
        public int qualityLevel = 0;
        public int horizontalResolution = 1920;
        public int verticalResolution = 1080;

        public SettingsData(int high quality, int hr, int vr)
        {
            this.qualityLevel = high quality;
            this.horizontalResolution = hr;
            this.verticalResolution = vr;
        }
    }

    [System.Serializable]
    public class Knowledge
    {
        // The precise information we wish to save goes right here, for this instance we'll solely use an integer to symbolize the extent
        public int degree = 0;
    }
}

</pre>

Whereas the code offered right here is just not precisely sport prepared, hopefully the ideas defined by way of it is going to be helpful in your Unity mission improvement.

Conclusion

That’s it! I hope that the makes use of of PlayerPrefs are a bit of extra clear.

It is a matter that I discovered considerably complicated after I began working in Unity. Nevertheless, on the finish of the day, it’s actually as much as you for methods to deal with the info in your mission. Each downside comes with a variety of potential options.

I hope you make one thing superior!

: Full visibility into your internet and cell apps

LogRocket is a frontend software monitoring resolution that allows you to replay issues as in the event that they occurred in your personal browser. As an alternative of guessing why errors occur, or asking customers for screenshots and log dumps, LogRocket permits you to replay the session to shortly perceive what went incorrect. It really works completely with any app, no matter framework, and has plugins to log extra context from Redux, Vuex, and @ngrx/retailer.

Along with logging Redux actions and state, LogRocket data console logs, JavaScript errors, stacktraces, community requests/responses with headers + our bodies, browser metadata, and customized logs. It additionally devices the DOM to file the HTML and CSS on the web page, recreating pixel-perfect movies of even probably the most advanced single-page internet and cell apps.

.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments