- Home /
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!
Answer by AVividLight · Aug 18, 2012 at 05:00 PM
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
Thanks for the scripts! And where can the http://System.IO be found? I've only added the first script, but it has a red squiggly all across under the line "void Save ()". And I'm still confused: where in the game would these scripts attach? Thanks for helping!
Sorry this has taken me so long to answer!
Void is for C#, in JavaScript it's the same as function These scripts would be attached to any gameobject, and called in some GUI code
-Edit- You can read more about System.IO on the $$anonymous$$icrosoftDeveloperNetwork ( http://msdn.microsoft.com/en-us/library/system.io.aspx )
Ahh I'm sorry I'm replying late as well. I've tried adjusting the script but there's still a bunch of errors showing up. What about the second script you wrote? Does that go on just another game object as well?
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
how to save a load a game? 1 Answer
Save game support, how do I load audio in a sertain time frame? 0 Answers
Best method to store files ? 2 Answers
Saving problem unity project 5 Answers