Save for Unity Version V.1.0.0

Introduction

Save for Unity is a suite of programs that enables the saving and loading of just about any data used by a Unity project.

The system consists of a basic Core module for which add-on modules may be purchased to extend the functionality as required.

Alongside the Core module the Pro and Expert assets come with several add-on modules included. The Complete asset will be continually updated to include new add-on modules as they become available.

Save for Unity uses a custom binary serialization system for fast, efficient and secure data encoding. Optionally, you may add your own encryption method to the system if required. The serialized data is stored in a proprietory file format, any attempt to modify a file will result in it becoming unusable.

The serialization system stores all of the data by value whilst preserving references between objects with as little reliance on reflection as possible.

This version of the utility was written in C# with Unity .Net 4.7.1 libraries and tested using Unity 2020.3 and 2021.3 for Standalone, WebGL, Android and IOS but should function on all platforms supported by Unity.

Whilst every effort has been made to ensure the compatibility of Save for Unity with all Unity versions, the correct functioning of the software with Unity Alpha, Beta or Technical releases cannot be guaranteed.

Please refer to the section Change Requests should you have a suggestion for a new add-on module or an enhancement to an existing one.

The code that makes up this utility is copyright SteveSmith.SoftWare 2022. Unless specifically stated in the code file or this documentation, no part of the system may be copied or modified. Neither may it be stored in such a way that would make it available to the public outside of the Unity Asset Store.

This documentation is available online at https://stevesmith.software. You will also find there the form for filing a bug report should it be necessary.

Steve Smith 2023.

Save for Unity Version 1.0.0 May 2023

<- Previous Next ->



Main Assets

Save for Unity is available in 4 main assets, the basic Core asset and 3 bundles.

Core

The Core asset includes serialization/deserialization for the following objects:-

Unity Objects

GameObject
Transform

Non Unity Objects

C# classes and structs with the System.Serializable attribute

Refer to the Supported Data Type section for a full list of primitives and Unity structs supported.

<- Previous Next ->



Pro

The Pro asset includes everything from the Core asset with the addition of

Unity Objects

Any class deriving from Monobehaviour

Add-On Modules

Graphics
Camera & Lights
Physics
Audio

Refer to the relevant add-on module section to see the objects handled by these add-ons.

<- Previous Next ->



Expert

The Expert asset includes everything from the Core asset with the addition of

Unity Objects

Any class deriving from Monobehaviour

Add-On Modules

Graphics
Camera & Lights
Physics
Audio
Events
UI including Text Mesh Pro
Animation
Navigation
Terrain

Refer to the relevant add-on module section to see the objects handled by these add-ons.

<- Previous Next ->



Complete

The Complete asset includes everything from the Core asset with the addition of

Unity Objects

Any class deriving from Monobehaviour

Add-On Modules

Graphics
Camera & Lights
Physics
Audio
Events
UI including Text Mesh Pro
Animation
Navigation
Terrain
Tile Maps
Joints and Hinges

Refer to the relevant add-on module section to see the objects handled by these add-ons.

This asset will be continually updated with additional add-on modules as they become available.

<- Previous Next ->



<- Previous Next ->



Save

Create an instance of this class to save data to a file

Namespace SSSoftware.Save

Class public class Save

Constructor


public Save(string fileName, Func<byte[], byte[]> encrypt = null)

Description
Create an instance of the Save class

Parameters
fileName The name of the file to write to.
The file will be saved in the Application.persistentData folder. If fileName contains a folder name this will be a sub-folder of the persistent data folder. If the sub folder does not exist it will be created. If the file already exists it will be overwritten.
encrypt An optional method to perform data encryption
If specified this method will be called to encrypt the data. Refer to the Encryption section for more information

Example


using SSSoftware.Save;

Save save = new Save("mySaveFile.sav", myEncrypt);

byte[] myEncrypt(byte[] bytes)
{
   // Perform Encryption here
   return encryptedBytes;
}


<- Previous Next ->



Methods

Game Objects may be given the Tag 'NoSave'. Any Game Object with this tag will be ignored by the save system this will also include it's children.

GameObject

The GameObject methods will save all of the GameObjects, their Components and Children


void GameObject(GameObject gameObject, bool keepOpen)

Description
Save a single GameObject

Parameters
gameObject The GameObject to save
keepOpen False to close the file on exit. True to keep the file open to add more data. Default: False

Return values
none

Example


            Save save = new Save("mySave");
            save.GameObject(gameObject);



void GameObject(List<GameObject> gameObjects, bool keepOpen)

Description
Save a list of GameObjects

Parameters
gameObjects The list of GameObjects to save
keepOpen False to close the file on exit. True to keep the file open to add more data. Default: False

Return values
none

Example


            List<GameObject> gameObjects = new List<GameObject>();
            // Fill the list

            Save save = new Save("mySave");
            save.GameObject(gameObjects);



void GameObject(GameObject[] gameObjects, bool keepOpen)

Description
Save an array of GameObjects

Parameters
gameObjects The array of GameObjects to save
keepOpen False to close the file on exit. True to keep the file open to add more data. Default: False

Return values
none

Example


            GameObject[] gameObjects = new GameObject[10];
            // Fill the array

            Save save = new Save("mySave");
            save.GameObject(gameObjects);



<- Previous Next ->



Object

The Object methods will save any serializable object which does not inherit from a Unity object.


void Object(object objects, bool keepOpen)

Description
Save a single serializable object

Parameters
objects The object to save
keepOpen False to close the file on exit. True to keep the file open to add more data. Default: False

Return values
none

Example


            MyClass myClass = new MyClass();
            Save save = new Save("mySave");
            save.Object(myClass);



void Object(List<object> objects, bool keepOpen)

Description
Save a list serializable objects

Parameters
objects The list of objects to save
keepOpen False to close the file on exit. True to keep the file open to add more data. Default: False

Return values
none

Example


            List<MyClass> myClasses = new List<MyClass>();
            // Fill list

            Save save = new Save("mySave");
            save.Object(myClasses);



void Object(object[] objects, bool keepOpen)

Description
Save an array of serializable objects

Parameters
objects The array of objects to save
keepOpen False to close the file on exit. True to keep the file open to add more data. Default: False

Return values
none

Example


            MyClass[] myClasses = new MyClass[10];
            // Fill array

            Save save = new Save("mySave");
            save.Object(myClasses);



<- Previous Next ->



Scene


void Scene(Scene scene, bool keepOpen)

Description
This method will save the complete contents of a scene

Parameters
scene The scene to save
keepOpen False to close the file on exit. True to keep the file open to add more data. Default: False

Return values
none

Example


using SSSoftware.Save;
using UnityEngine.SceneManagement;

Scene scene = SceneManager.GetActiveScene();
Save save = new Save("mySave");
save.Scene(scene);


<- Previous Next ->



<- Previous Next ->



Properties

The Save class has a static property, Trace. Set this to true to get a verbose log of the actions taken by the system.

<- Previous Next ->



<- Previous Next ->



Load

Create an instance of this class to load data from a file

Namespace SSSoftware.Save

Class public class Load

Constructor


public Load(string fileName, Func<byte[], byte[]> decrypt = null)

Description
Create an instance of the Load class

Parameters
fileName The name of the file to read from.
The file should be located in Application.persistentData folder or a specified sub-folder. If the file does not exist an exception will be thrown
decrypt An optional method to perform data decryption
If specified this method will be called to decrypt the data. Refer to the Encryption section for more information

Example


using SSSoftware.Save;

Load load = new Load("mySaveFile.sav", myDecrypt);

byte[] myDecrypt(byte[] bytes)
{
   // Perform Decryption here
   return decryptedBytes;
}


<- Previous Next ->



Methods

GameObject

The GameObject method will load the GameObject, it's Components and all of it's children


GameObject GameObject(string name)

Description
Load a single GameObject by name

Parameters
name The name of the GameObject to Load

Return values
GameObject The Loaded GameObject

Example


            Load load = new Load("mySave");
            GameObject go = load.GameObject("myGameObject");



List<GameObject> GameObject()

Description
Load all of the GameObjects into the active scene

Parameters
none

Return values
List<GameObject> The list of Loaded GameObjects

Example


            Load load = new Load("mySave");
            List<GameObject> gameObjects = load.GameObject();


<- Previous Next ->



Object

The Object method will load the serializable objects in the file.


List<object> Object()

Description
Loads all of the serializable objects and return them as a list

Parameters
none

Return values
List<object> A list of the loaded objects

Example


            Load load = new Load("mySave");
            List<object> objects = load.Object();



List<object> Object(Type type)

Description
Loads all of the serializable objects of the specified Type and return them as a list

Parameters
type The Type of the objects to load

Return values
List<object> A list of the loaded objects

Example


            Load load = new Load("mySave");
            List<object> objects = load.Object(typeof(MyClass));



List<T> Object<T>()

Description
Loads all of the serializable objects of the specified Type and return them as a list

Parameters
none

Return values
List<T> A list of the loaded objects

Example


            Load load = new Load("mySave");
            List<MyClass> objects = load.Object<MyClass>();



<- Previous Next ->



Scene


void Scene(Scene scene)

Description
This method will load the saved data into the scene

Parameters
scene The scene to load into

Return values
none

Example


using SSSoftware.Save;
using UnityEngine.SceneManagement;

Scene scene = SceneManager.GetActiveScene();
Load load = new Load("mySave");
load.Scene(scene);

<- Previous Next ->



<- Previous Next ->



Interfaces

ILoad

Whilst every effort has been made to restore references between objects on Load it may not always be possible to do so. The ILoad interface may be added to a Monobehaviour class to provide a callback once loading is complete in order for that class to fix any missing references or carry out any other kind of re-initialization processes.


void OnLoadComplete()

Description
Called by the Load class once all loading of data is completed

Parameters
none

Return values
none

Example


using UnityEngine;
using SSSoftware.Save;

public class NewBehaviourScript : MonoBehaviour, ILoad
{
    public GameObject target;

    public void OnLoadComplete()
	{
		target = GameObject.Find("Target");
	}
}


<- Previous Next ->



<- Previous Next ->



Properties

The Load class has a static property, Trace. Set this to true to get a verbose log of the actions taken by the system.

<- Previous Next ->



<- Previous Next ->



Encryption

Due to the propriatory nature of the Save for Unity file format and serializer and the fact that encrypting and decrypting data is an intensive task this system does not include an encryption module.

However, hooks have been provided in the constructors of the Save and Load classes to allow the user to define their own encryption routines if required.

As a part of the Save finalization process a byte array will be passed to an encryption method written by the user and that method should return a byte array of that encrypted data which will then by written to the save file.

As a part of the Load initialization process the encrypted byte array will be passed to a decryption method written by the user and that method should return a byte array of that decrypted data. This data is then used to load the file.

It is the responsibility of the encryption and decryption methods provided by the user to ensure that the decrypted data matches exactly with the data passed for encryption.

Once a save file has been saved with encrypted data it will be impossible to use that file without the corresponding decryption method.


<- Previous Next ->



Add-On Modules

The Add-on modules are NOT stand alone assets. You must use them in combination with one of the main Save for Unity assets.

Animation

The Animation module provides support for the following objects

UnityEngine.Animation
UnityEngine.AnimationClip
UnityEngine.Animator
UnityEngine.AnimationCurve
UnityEngine.Animations.AimConstraint
UnityEngine.Animations.AnimationClipPlayable
UnityEngine.Animations.AnimationLayerMixerPlayable
UnityEngine.Animations.AnimationMixerPlayable
UnityEngine.Animations.AnimationPlayableOutput
UnityEngine.Animations.AnimationScriptPlayable
UnityEngine.Animations.AnimatorControllerPlayable
UnityEngine.Animations.LookAtConstraint
UnityEngine.Animations.ConstraintSource
UnityEngine.Animations.MuscleHandle
UnityEngine.Animations.ParentConstraint
UnityEngine.Animations.PositionConstraint
UnityEngine.Animations.PropertySceneHandle
UnityEngine.Animations.PropertyStreamHandle
UnityEngine.Animations.RotationConstraint
UnityEngine.Animations.ScaleConstraint
UnityEngine.Animations.TransformSceneHandle
UnityEngine.Animations.TransformStreamHandle
UnityEngine.Avatar

<- Previous Next ->



Audio

The Audio module provides support for the following objects

UnityEngine.AudioClip,
UnityEngine.AudioSource,
UnityEngine.Audio.AudioMixer,
UnityEngine.Audio.AudioMixerGroup,
UnityEngine.Audio.AudioClipPlayable,
UnityEngine.Audio.AudioMixerPlayable,
UnityEngine.Audio.AudioMixerSnapshot,
UnityEngine.Audio.AudioMixerUpdateMode,
UnityEngine.Audio.AudioPlayableOutput,
UnityEngine.AudioBehaviour,
UnityEngine.AudioChorusFilter,
UnityEngine.AudioConfiguration,
UnityEngine.AudioDistortionFilter,
UnityEngine.AudioEchoFilter,
UnityEngine.AudioHighPassFilter,
UnityEngine.AudioLowPassFilter,
UnityEngine.AudioReverbFilter,
UnityEngine.AudioReverbZone,

<- Previous Next ->



Camera & Light

The Camera module provides support for the following objects

AudioListener
Camera
Light

Note: The Light class may cause problems in a build when using URP or HDRP. It is recommended that it not be used in this situation.

<- Previous Next ->



Events

The Events module provides support for all objects deriving from UnityEngine.Events.Event

This add-on module is included in the UI add-on miodule

<- Previous Next ->



Graphics

The Graphics module provides support for the following objects

Material
Mesh
MeshFilter
MeshRenderer
Shader
Sprite
Texture2D
SkinnedMeshRenderer

Note: For Texture2D assets to be serialized including the image data they must be flagged as Read/Write in their inspector

<- Previous Next ->



Joints

The Joints module provides support for the following objects

3D

CharacterJoint
ConfigurableJoint
FixedJoint
HingeJoint
SpringJoint

2D

DistanceJoint2D
FixedJoint2D
FrictionJoint2D
HingeJoint2D
RelitiveJoint2D
SliderJoint2D
SpringJoint2D
TargetJoint2D
WheelJoint2D


<- Previous Next ->



Monobehaviours

The Monobehaviour module give support for any class which derives from UnityEngine.Monobehaviour

<- Previous Next ->



Navigation

The Navigation module provides support for the following objects

NavMeshAgent
NavMeshData
NavMeshHit
NavMeshObstacle
OcclusionArea
PositionAsUV1

<- Previous Next ->



Physics

The Physics module provides support for the following objects

3D

BoxCollider
CapsuleCollider
MeshCollider
PhysicsMaterial
PhysicsRaycaster
Rigidbody
SphereCollider
WheelCollider
CharacterController

2D

BoxCollider2D
CapsuleCollider2D
CircleCollider2D
CompositeCollider2D
EdgeCollider2D
PhysicsMaterial2D
Physics2DRaycaster
PolygonCollider2D
Rigidbody2D

<- Previous Next ->



Terrain

The Terrain module provides support for the following objects

DetailPrototype
Terrain
TerrainCollider
TerrainData
TerrainLayer
TreeInstance
TreePrototype

<- Previous Next ->



Tile Maps

The Tiles module provides support for the following objects

Tile
TileAnimationData
TileData
Tilemap
TilemapCollider2D
TilemapRenderer

<- Previous Next ->



UI

The UI module provides support for the following objects

IMGUI

Button
Canvas
CanvasRenderer
CanvasScaler
CharacterInfo
ColorBlock
Dropdown
EventSystem
Font
FontData
GraphicRaycaster
Image
Inputfield
Mask
Navigation
OptionData
OptionSataList
RawImage
RectTransform
Scrollbar
ScrollRect
Slider
SppriteState
StandaloneInputModule
Text
Toggle
UIVertex

TMP

TextMeshProUGUI
TMP_ColorGradient
TMP_Dropdown
TMP_Inputfield
TMP_Sprite
TMP_Style
TMP_StyleSheet
TMP_Text
VertexGradient

This module also includes the Events add-on module

<- Previous Next ->



<- Previous Next ->



Example Code

Simple Save and Load


using UnityEngine;
using SSSoftware.Save;
using UnityEngine.SceneManagement;

public class SaveAndLoad : MonoBehaviour
{
    public enum Run
    {
        None,
        Save,
        Load
    }

    public Run saveOrLoad;
    public string saveFileName;

    void Start()
    {
        Scene scene = SceneManager.GetActiveScene();
        if (saveOrLoad == Run.Save)
        {
            //Save.Trace = true;
            Save save = new Save(saveFileName);
            save.Scene(scene);
        }

        else
        {
            if (saveOrLoad == Run.Load)
            {
                //Load.Trace = true;
                Load load = new Load(saveFileName);
                load.Scene(scene);
            }
        }
    }
}
Add this code to an empty game object and tag it 'NoSave'. Select the required function and file name in the inspector



<- Previous Next ->



<- Previous Next ->



Supported Data Types

C# Data types

The following C# data types are supported by Save for Unity

Primitive Data Types

byte
sbyte
char
ushort
short
uint
int
ulong
long
decimal
float
double
string

C# Classes

User defined classes must have the [Serializable] attribute.
DateTime
TimeSpan

Array where T is a C# primitive type
This includes
Array[] with any number of ranks
and jagged arrays of any depth

List where T is a C# primitive type

Dictionary where T1 and T2 are C# primitive types

To have these data types extended please refer to Change Requests

<- Previous Next ->



Unity Data types

The following Unity data types are supported by Save for Unity

Vector2
Vector2Int
Vector3
Vector3Int
Vector4
Quaternion
Color
Color32
Rect
Rectint
Matrix4x4
Bounds
BoundsInt
BoneWeight
BoneWeight1
KeyFrame

The utility also supports

Array where T is one of the above.
This includes
Array[]
Array[,]
Array[,,]
And jagged arrays

List where T is one of the above

Dictionary where T1 and/or T2 are one of the above or C# primitive types

NativeArrayt where T is one of the above or a C# primitive type

To have these data types extended please refer to Change Requests

<- Previous Next ->



<- Previous Next ->



Additional Information

Support

Support can only be offered to users using Unity LTS versions

Please contact SteveSmith.Software via one of the following channels

To file a Bug Report: SteveSmith.Software Choose the Contact tab and login as guest

Email: Support@SteveSmith.Software

Discord: Join our discord channel at SteveSmith.Software on discord

<- Previous Next ->



Change Requests

Save for Unity aims to be the ultimate serializer/deserialzer for Unity projects.

Any request for additional data type implementation or support will be treated as a matter of urgency

Please email Support@SteveSmith.Software with your request

<- Previous Next ->



<- Previous Next ->