Introduction
Saving and retrieving data is something that every Unity Developer has to struggle with at some point of time. By the nature of how Unity and how computers work, most of your data change is volatile. Even changes made in Editor Play mode are not permanent.
We need to save data in order to track progress and record important values, which are critical to the gameplay. Data is lost between scenes because on every scene load Unity will destroy previous scene’s game objects, except when it’s explicitly specified. This in turn leads to destruction of MonoBehaviours and thus the data. Data is lost between gameplay sessions because the memory allocated on RAM for a Unity application at run time is freed up by the OS when application is closed. So the problem of saving and retrieving data can be broadly classified into two categories
Scene to Scene
In part 2, methods of saving data permanently will be discussed. Static Class
Static classes have number of special properties:
Since they are not attached to a game object they are safe from scene cleanup (deletion of every game object at scene load). They also have a global access. These make them suitable as data holders. Accessing data stored in static classes is very easy. Since static classes can’t extend MonoBehaviour, they have a few downsides
Creating a static classSaving & Retrieving DataSingleton Pattern
It is a popular design pattern with widespread use in game development. The main criteria of a singleton class are:
Singleton is basically a unique static instance of a class. Due to a global point of access no reference is needed for saving or retrieving data, this makes them very convenient to use. One of the methods of implementation of singleton pattern is provided below. Creating a singletonSaving & Retrieving DataScriptable Object
Scriptable Object is a class that lets you create objects that don’t need to be attached to a game object. Their primarily used as data containers. As data containers they are extremely helpful in using the programming principle of “Separation of data and code”. Numerous benefits of this principle include safety of source code, ease of editing, scaling and maintenance.
Scriptable objects create data container assets. These assets are what hold data. Since these are assets, they are immune to scene cleanup and they also preserver their values during a scene load. The only downside of scriptable objects is that they don’t have a global point of access. However in conjugation of either singleton pattern or static classes, it is possible to use scriptable objects for cross scene data holder which also have global access. Creating a scriptable objectSaving & Retrieving Data |
Follow updates
Categories
All
Archives
February 2017
|