facebooktwittergoogle_pluspinterestyoutubeby feather

This is the documentation of a new asset we wrote to persist level data in Unity 3d. We used it in our game Erwin’s timewarp and it will be available soon in the assetstore.

The goal of the framework is to save data for gameobjects with a given name for the current level.

And here is how the the solution works:

Add LevelManager

Locate the LevelManager prefab in the prefabs folder and drag it to your scene:

Prefabs LevelSave asset

Prefabs LevelSave asset

The LevelManager does all the work for loading and saving properties for you gameobjects you like to persist.

Persist objects

For objects you would like to store data you just have to implement an interface called IPersistable, here is an example of a cube for which the rotation and position is persisted with 2 lines of code:

using UnityEngine;
using System.Collections;
using JNM.Storage;

public class CubePersistable : MonoBehaviour, IPersistable {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}

    public void ReadFromStorage(StorageContainer container)
    {
        // get stored postion and rotation with 2 lines
        transform.position = container.GetVector3("pos");
        transform.rotation = container.GetQuaternion("rot");
    }

    public void WriteToStorage(StorageContainer container)
    {
        // store the position and rotation with 2 lines
        container.AddVector3("pos", transform.position);
        container.AddQuaternion("rot", transform.rotation);
    }
}

Very easy isn’t it? As you can see in the code above you can store properties of you gameobjects with typed methods of the StorageContainer class.

The last thing you need to do is to save the game with a special name and to load it again when needed:


// Call LevelManager with a name to save
LevelManager.Instance.SaveGame("NameOfTheGame");

// ...

// Load the game with a special name
LevelManager.Instance.LoadGame("NameOfTheGame");

If want to save just the last state of the game without referring to a special name you can use always the same name as key of course.

Sample scenes

We added 2 sample scenes to the asset, an Intro scene in which you can select saved games and load them in the game scene. This second scene contains some persistable gameobjects for which the rotation and the position is stored by the LevelManager:

Intro scene with saved games

Intro scene with saved games

Persisted game objects loaded by LevelManager

Persisted game objects loaded by LevelManager

The UI widgets to display the saved games and the panel to save a game with a special name are also part of the asset.

Here you can see the asset in action:

facebooktwittergoogle_plusredditpinterestby feather