Skip to main content

Saving and Loading

Saving and loading uses the GameObject's name in the scene to store the maximum and current values of the VitalsComponent on the object.

Important

GameObjects that get instantiated at runtime and might get a different name ( based on instantiation order "GameObject (1)" "GameObject (2)" ), saving and loading will not work as intended.

If that is the case, it is better to implement your own save system and avoid using the built-in one.

Basic Usage

Saving

There are two ways to save the Vitals Component values.

Ticking the "Save On Quit" box in the component editor will save the Vitals Component values when the game closes.

NOTE: The object must exist in the scene when the application quits. For example, if you want to save on return to the main menu use the manual saving.

To manually save the Vitals values on an object, get a reference to the Vitals Componenet on the object and use the VitalsSaveUtility's Save method.

private Transform playerCharacter

private void OnSaveGame(){
Health health = playerCharacter.GetComponent<Health>();

Stamina stamina = playerCharacter.GetComponent<Stamina>();

VitalsSaveUtility.Save(health);

VitalsSaveUtility.Save(stamina);
}

This will save a binary file called "[GameObject Name]_[Vitals Component Type].data" in the Application.persistentDataPath folder.

File name example: playerCharacter_Health.data

Loading

There are two ways to load the saved Vitals Component values.

Ticking the "Load On Start" box in the component editor will try to load any saved data for that GameObject based on the name.

If no save data is found, the component will load the values from the Config asset.

You can manually load the values of a Vitals Component using the VitalsSaveUtility's Load method.

The Load methods returns true if a save file was found and loaded successfully, and returns false if no save data is found.

private Transform playerCharacter

private void OnGameSetup(){
Health health = playerCharacter.GetComponent<Health>();

Stamina stamina = playerCharacter.GetComponent<Stamina>();

if(VitalsSaveUtility.Load(health)){
// If load succeeds...
} else{
// If load fails...
}

// If there is no need to handle success/fail
VitalsSaveUtility.Load(stamina);
}