Hello. Excuse me if this is a stupid question, but how can I save ingame data when exit, and load again when launch game?
For example, in a scene a Door (or 100) can be OPEN or CLOSED.
There is a way to go through the scene objects list and get their values? Must I use std::fstream in script to save a bin file or there is another way? It is better do this in scene script? Can I do this in visual scripting?
We have som utilities for implementing savesystem for a game (kind of game-specific feature, not a general solution to be in engine). My tips are:
- You can use Tags to mark actors as
savable
- for gameplay objects like doors, player, erc. so you can iterate over objects on the scene and get the list of them to save - Actors and Scripts are inheriting from SceneObject and implement
ISerializable
interface in C++ that contains nice ways of data serialization for the gameplay state. Example code:
rapidjson_flax::StringBuffer buffer;
CompactJsonWriter writer(buffer);
writer.SceneObject(myActorOrScript);
String mySavedStatAsString(buffer.GetString());
- We have some in-build methods to save objects state (eg. used by editor undo system):
Actor::ToBytes
,Actor::FromBytes
,Actor::ToJson
,Actor::FromJson
Finally, here I showed C++ more like examples but those methods are also available in C# and Visual Script. The only problem in Visual Script might be the lack of good Arrays support (work in progress). So I would suggest implementing saveystsem in C# or C++.
I think it’s clear. My next question was about arrays in visual script, but I’ll wait then xD
Thank you, I’ll coming back to engine.
Is there an easy way to save just one variable like Unity’s PlayerPrefs? I’m wanting to save a high score variable.
We don’t have PlayerPrefs
but the game can use file stored in-app data folder which can be a simple json or even plain text.
An example would be:
public static class GameSettings
{
private static Dictionary<string, string> _data;
private static string _path;
public static Dictionary<string, string> Data
{
get
{
if (_data == null)
Load();
return _data;
}
}
/// <summary>
/// Loads the settings.
/// </summary>
public static void Load()
{
if (_data != null)
return;
_path = Path.Combine(Globals.ProductLocalFolder, "Game.settings");
_data = new Dictionary<string, string>();
if (File.Exists(_path))
{
var json = File.ReadAllText(_path);
FlaxEngine.Json.JsonSerializer.Deserialize(_data, json);
}
}
/// <summary>
/// Saves the current settings.
/// </summary>
public static void Save()
{
if (_data == null)
return;
var json = FlaxEngine.Json.JsonSerializer.Serialize(_data);
var dir = Path.GetDirectoryName(_path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(_path, json);
}
}
Thank you very much! This is kind of how Godot does their save system, so this shouldn’t be too hard for me to use.