hi, i am trying to make a simple multiplayer proyect in which each player haves an inventory and can modify the scene, my question is how can i save the state of the scene(also saving each player’s inventory) so next time the same host opens the server everything is there?
There’s no way to directly save the “scene” as if you’re in the editor from a standalone build. What you can do is record all changes to the scene that you want to preserve to disk, as well as the inventory, and then read that back when the game is reloaded. So you’d record the location and rotation of objects, what type of prefab, etc. Using either JSON format or writing to a database is probably your best bet.
1 Like
I wrote a class where you can specify your datatype and save it to the device (should work on all platforms)
Use it as follow:
WriteLoad.SaveData<YOUR_TYPE>(REFERENCE);
WriteLoad.LoadData<YOUR_TYPE>();
YOUR_TYPE can be anything you define. A string, List of data, Dict, custom class, etc…
Write Load class:
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using System.IO;
using UnityEngine;
public class WriteLoad : MonoBehaviour {
//Location of file on windows
//C:\Users\your name\AppData\LocalLow\DefaultCompany\project_name
public static void SaveData<T>(T data)
{
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Create (Application.persistentDataPath + Parameters.dataName);
bf.Serialize (file, data);
file.Close ();
}
public static T LoadData<T>()
{
if (File.Exists (Application.persistentDataPath + Parameters.dataName)) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + Parameters.dataName, FileMode.Open);
T data = (T)bf.Deserialize (file);
file.Close ();
return data;
}
T dataEmpty = default(T);
return dataEmpty;
}
}
I encourage you to make a Class with constant values to set common data such as dataname
Example
public class Parameters
{
public static const string dataName = "myDataName";
}
Enjoy
2 Likes