Answer the question
In order to leave comments, you need to log in
How to save a dictionary with prefabs in a text document?
I have a dictionary like DictionaryPrefabs = new Dictionary(); , ClassPrefab is a prefab with a class, it has a variety of variables (int, string, bool, Dictionary, Array....), I need to save the state of the DictionaryPrefabs dictionary with all prefabs and data in them, how to do this?
Or maybe you can just save the scene itself?
I have a game scene and a "save and exit" function, the player can either load a save or start the scene from scratch, i.e. there are no multiple saves...
Answer the question
In order to leave comments, you need to log in
You can save manually via BinaryWriter, BinaryReader or Json. Prefabs themselves cannot be saved, but their data can.
Here's a simple implementation of how you can save the data. (I did not check the code for performance, but nevertheless)
public interface IData
{
void Read(BinaryReader reader);
void Write(BinaryWriter writer);
}
public class CustomClass : IData
{
private int _customVar;
public void Write(BinaryWriter writer)
{
writer.Write(_customVar);
}
public void Read(BinaryReader reader)
{
_customVar = reader.ReadInt32();
}
}
public class PrefabClass: MonoBehaviour, IData
{
private int _intValue;
private float _floatValue;
private string _stringValue;
private CustomClass _customClass;
public void Write(BinaryWriter writer)
{
writer.Write(_intValue);
writer.Write(_floatValue);
writer.Write(_stringValue);
((IData)_customClass).Write(writer);
}
public void Read(BinaryReader reader)
{
// Читать нужно в том же порядке что и пишется
_intValue = reader.ReadInt32();
_floatValue = reader.ReadSingle();
_stringValue = reader.ReadString();
// Свои данные
// ...
((IData)_customClass).Read(reader);
}
}
public class DictionaryClass
{
private Dictionary<string, IData> _dict = new Dictionary<string, IData>();
public void Save()
{
using (BinaryWriter writer = new BinaryWriter(File.Open("Path", FileMode.Create)))
{
foreach(var item in _dict)
{
item.Write(writer);
}
}
}
public void Load()
{
if (File.Exists("Path"))
{
using (BinaryReader reader = new BinaryReader(File.Open("Path", FileMode.Open)))
{
foreach(var item in _dict)
{
item.Read(reader);
}
}
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question