简体   繁体   中英

Saving the progress of a Unity game in isolated storage

I am building a Unity game targetted for Windows Store 8.1 and I need to save game progress in isolated storage. But using 'await' operator in accessing the local storage gives me this error

'await' requires that the type 'Windows.Foundation.IAsyncOperation<Windows.Storage.StorageFile>' have a suitable GetAwaiter method. Are you missing a using directive for 'System'?

Is there a way i can use 'await' operator somehow?

I figured if I implement my Save method in the solution generated after exporting the project to Windows 8.1 it would work fine. Trouble is I am not sure how to access the variables and methods(required in saving the game) of the unity script in the main solution.

Can anyone help with any of these approaches or if there is a better one?

EDIT: Here is the code I am using:

public async void save_game()
{
    StorageFile destiFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("Merged.png", CreationCollisionOption.ReplaceExisting);
    using (IRandomAccessStream stream = await destiFile.OpenAsync(FileAccessMode.ReadWrite))
    {
        //you can manipulate this stream object here
    }
}

Is it necessary to use isolated storage. easiest way to save game in unity is using playerprefs. it works on any platform.

PlayerPrefs.SetString("Player Name", "Foobar");

Unity's version of Mono/.NET doesn't support async/await, which is why you get the first error.

Others have figured out how to "trick" Unity into letting you indirectly call async functions. One such method is listed on UnityAnswers

You could use something like this.

// this is for loading
    BinaryFormatter binFormatter = new BinaryFormatter();
                string filename = Application.persistentDataPath + "/savedgame.dat";
                FileStream file = File.Open(filename, FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
                GameData data = (GameData)binFormatter.Deserialize(file) ;
                file.Close();

where the GameData class is [Serializable]. and after you Deserialize it you can load its members into ingame variables.

//And this is for saving
BinaryFormatter binFormatter = new BinaryFormatter();
        string filename = Application.persistentDataPath + "/savedgame.dat";
        FileStream file = new FileStream(filename, FileMode.Create,FileAccess.Write,FileShare.ReadWrite);
        GameData data = new GameData();

// here it will be something like data.health = player.health file.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM