How to write a simple save script

Hey there, I’ve browsed around but I have been unsuccessful in the means of finding a “save” code. I was wondering if there was a way through JavaScript to save the level the player is currently on (perhaps by clicking a button) and giving the option to start from the very beginning again or load the saved game (after the game is rebooted, of course). Thanks for your help!

Hey Justin,

Okay, so there are two ways to do this, I’ll explain both, but I’d suggest the latter, as it is much easier and lightweight.


You’ll need to create a basic text file using System.IO, and write the number of the level to that.

//I don't use Unity's JavaScript, so I can't really translate this, but it should be about the same, as C# and Unity's JavaScript both use .NET

using System.IO;

    void Save ()
    {

        if (!Directory.Exists(locationOfSaveFIle))
        {

	    	Directory.CreateDirectory(locationOfSaveFile);
			Save();
		} else {
			using (StreamWriter saveFile = File.CreateText(saveFileLocation))
				saveFile.WriteLine(levelNumber);
		}         
    }
void Load ()
{

 using (FileStream fs = new FileStream(path, FileMode.Open)) 
            {
                using (StreamReader sr = new StreamReader(fs)) 
                {

                    while (sr.Peek() >= 0) 
                    {
                        Application.LoadLevel(sr.ReadLine());
                    }
                }
            }
}

Using PlayerPrefs.SetInt/GetInt

void Save ()
{

    PlayerPrefs.SetInt("SavedLevel", LevelInt);
}

void Load ()
{

    Application.LoadLevel(PlayerPrefs.GetInt("SavedLevel"));
}

Note: I haven’t tested any of this, if you try it and it doesn’t work, I’ll be glad to help!

Hope you figure it out, Gibson