Save & Loading Variables


I want to have the ability to save my game variables when I leave the game. I'm not worried about positions of objects or anything like that. I literally want to grab all the variables I have in my scripts, and save them as an XML or something so next time, when I open up my game all my variables will be replaced with the saved ones.

I've tried messing around with a Save Load script, but I just can't get it to work. So like I said, is there a way to pull all my current game variables, and save them - and then load them back up?

Would appreciate any help or info.


-- EDIT --

So, Ive been messing around with the PlayerPrefs, and im not 100% sure on how it works. This is how I have my setup.

-- EDIT Update --

So i have this to save the current variables (well 1 at this current time):

if (GUI.Button(Rect(10,70,50,30),"Save")){
        PlayerPrefsX.SetBool("inventoryKnife", StoryControl.inventoryKnife);

On my landing scene (0) - how would I go about loading the variables up into the game?

function Start(){
     Application.LoadLevel(PlayerPrefs.GetInt("inventoryKnife")); //??
     Application.LoadLevel(PlayerPrefsX.GetBool ... //?

I have no idea how PlayerPrefs work.

Are you sure you aren't supposed to call SetInt? I am under the impression you want to set the saved level on Save. And you can provide a default value to GetInt if it doesn't exist so you don't have to check if the key exists. It will also get rid of your static variable.

function Start()
    // If no savedLevel was found it will return 1 as default.
    Application.LoadLevel(PlayerPrefs.GetInt("savedLevel", 1));

And if you want to set the savedLevel to something, for instance set it to level 2:

if (GUI.Button(Rect(10,70,50,30), "Save"))
    PlayerPrefs.SetInt("savedLevel", 2);

PlayerPrefs is kind of easy. You can think of it as having static variables that are saved between games. There is a Get and a Set for Int, Float and String. For ease, GetInt etc accept an optional parameter that is the default value if no key was found.

See also BoolPrefs and ArrayPrefs.

Given you have a script you want to save/load savegame data to/from:

// The data we want to save.
var inventoryKnife : boolean;

function OnEnable()

function OnDisable()

function Load()
    inventoryKnife = PlayerPrefsX.GetBool("inventoryKnife", false);

function Save()
    PlayerPrefsX.SetBool("inventoryKnife", inventoryKnife);

hi, you can use PLAYERPREFS.