Player Persister

The Player Persister is used to persist the state of the Player. This concept can be used for all other objects too, to persist its state. It’s written to a file, but it can be easily be extended to write to a DB or another Service.

Prefab and Scripts

The main class of the persister is the GameController Prefab. On that Prefab there is a script called NononZonePersister.

Additionally on each component you want to persist, there has to be a persister Script, that derives from INononZonePersister. In the case of the Character controller a script named PlayerPersister is on that object.

How does it work…..

In the game at certain events, you want to persist your player (e.g. at looting something). When this happens you can use the NononZonePersister to persist your state into a file. For this you can use the Method “WriteTransform2Json()”.

public void WriteTransform2Json(Transform obj2Write, string playerID)

NononZonePersister.Instance.WriteTransform2Json(source, source.GetComponent<NononZoneObject>().GetNononZoneObjectName());

The method takes two parameters:

obj2Write: The transform on which the script looks for the INononZonePersisters and calling the Serialize2JSON Method.

playerID: The name of the player, meaning an identifier for the filename

So, if the Method WriteTransform2Json is called, the script goes looking for all Scripts that have INononZonePersister implemented and is calling Serialize2JSON() on that script. The persister writes down then the serialized JSON into a file. The file is located at the Application persistent data path for the moment.

The reverse process is used when restoring the Values from the file. This happens in the Method RestoreValuesOnTransformFromJson().

public void RestoreValuesOnTransformFromJson(Transform obj2Restore, string playerID)

NononZonePersister.Instance.RestoreValuesOnTransformFromJson(playerInstance.transform, playerInstance.GetComponent<NononZoneObject>().GetNononZoneObjectName());


Leave a Reply

Avatar placeholder