Custom Serializable Objects

When using the AddOrUpdateData method to save Unity types such as Transform, Vectors, etc., ESave converts each to a savable type automatically. However, this will not happen if you try saving a custom serializable object that has unsavable Unity types as fields.

Solution

You will have to manually convert each to a savable type.

Example Saving

Here we have a custom serializable class with unsavable Unity types.

[System.Serializable]
public class TestClass
{
    public Vector3 position;
    public Quaternion rotation;
    public Color color;
}

If you try saving this class, ESave will throw an error. To fix this, we can use the SavableVector class for both fields.

[System.Serializable]
public class TestClass
{
    public SavableVector position;
    
    // A Quaternion is similar to Vector4 (x, y, z, w)
    public SavableVector rotation;
    
    // A Color is similar to Vector4 (r, g, b, a)
    public SavableVector color;
}

This will allow your class to be saved with ESave. For Transform, you can use SavableTransform.

[System.Serializable]
public class TestClass
{
    public SavableVector position;
    public SavableVector rotation;
    public SavableVector color;
    public SavableTransform transform;
}

The SavableTransform saves the position and rotation, so the first 2 fields are technically not necessary, but we will leave them here just for informational purposes.

Now that we have our class, let's give it some data and then save it.

// Create a color that we will save
var myColor = Color.blue;

// Create the savable class
var testClass = new TestClass
{
    // Converting each to a savable type
    position = transform.position.ToSavable();
    rotation = transform.rotation.ToSavable();
    color = myColor.ToSavable();
    transform = transform.ToSavable();
};

// Set the ID we will use for retreival
string testClassID = "test";

// Save the data
saveFile.AddOrUpdateData(testClassID, testClass);

Example Loading

Here's how we can load the TestClass from above:

// Load the data
var test = saveFile.GetData<TestClass>(testClassID);

// Assign loaded values
transform.position = test.position.vector3Value;
transform.rotation = test.rotation.quaternionValue;
var myColor = test.color.colorValue;
transform.CopyTransformValues(test.transform);

Last updated