Monday, July 4, 2011

How To Save Game Data Local on Same Machine

While Unity is used for more than games, it's clearly targeted at 3D games. So savegames (and loadgames) should be addressed, even if it's in the form of a tutorial. But it's not even in Unity's FAQ.

Right now UT's answer is with PlayerPrefs, but from what I've seen of it, it's clearly not an optimal solution. PlayerPrefs doesn't really give you much support for doing multiple save games, complex data structures, etc.

I imagine "support for savegames" in Unity would be:

1. An easy way to tag GOs "saveable", including script state.
2. A way to save those off to a file, and load it back in.

Even if this functionality were only on a per-script basis it would save a lot of code maintenance.

And it seems like the editor *almost* already supports all this, minus script state.

Seems feasable to me

However, barring complete automatic save and load, I'd love to know how to roll your own. Specifically, something like this:

1. A piece of code that can crawl the Hierarchy. (I've looked for code examples of this and have not seen it)
2. A way to inspect objects and what variables they contain.

What I want to avoid is having to more save and load code every time I write a new script.

Can anyone point me to some code samples to do this kind of stuff?

2nd Solution : 

In Declaration you need to declare like this 

public class MainmenuScript : MonoBehaviour 
    DataPersistance dataPersistance; /// Persistance Object : Read/Write to file.
    GameConfig gameConfig=null; ///object to for game settings info.

First You need to Declare this in your Start

void Start ()
        dataPersistance = new DataPersistance();
        gameConfig = dataPersistance.LoadInfo();
        if(starts > 0)
        screenID = gameConfig.screenID;   

Now Wherever you want to save that u need to write there this code

PlayerPrefs.SetFloat("difficultyLevel", difficultyLevel);
gameConfig.CurrentPlayer = CurrentPlayer = gameConfig.MaxPlayerNo;
gameConfig.fxLevel = soundFXValue;
gameConfig.volumeLevel = soundVolume;gameConfig.difficultyLevel = difficultyLevel;
gameConfig.playerName = stringToEdit;
Debug.Log("name is :"+gameConfig.playerName);
gameConfig.score = score;dataPersistance.SaveInfo(gameConfig);

So that GameConfig will help you to save data on your local machine .. and for more i have share code just go through it ..

You Can Down Load Code From Here.

Vivek P Shah
Game Developer in Unity3d and Cocos2d


Post a Comment