AutoReset classes
Last updated
To understand the usage of these classes, it's important to understand Unity's Enter Play Mode Options and the effect that not reloading the domain can have on ScriptableObjects.
The lifetime of a ScriptableObject, unlike a GameObject in the scene, doesn't start and finish with Play Mode. An SO can call its OnEnable() only once when the editor is started (or when code recompiles), so its state is not cleared when entering Play Mode (like it happens to GameObjects and their scripts).
For more information, read all about Unity's Enter Play Mode Options and especially disabling Domain Reload on their documentation.
To deal with these complications, ScriptableObject Tools provides three base classes AutoResetOnEnterPlayMode AutoResetOnExitPlayMode and AutoResetOnBoth. They expose methods that will be invoked when entering or exiting Play Mode, offering you a chance to reset the SO's state.
To use one of the AutoReset classes, simply inherit from them and implement the abstract methods contained within: OnEnterPlayMode(), OnExitPlayMode(), or both; depending on the class.
For instance, if you wanted to make an SO that holds the score of the game, you want to make sure to reset it when the editor exits Play Mode, like this:
[CreateAssetMenu]
public class MySmartSO : AutoResetOnExitPlayMode
{
public int score;
public void AddPoints(int points) => score += points;
protected override void OnExitPlayMode()
{
score = 0;
}
}This way, even if no code resets the score, upon exiting Play Mode the OnExitPlayMode() will take care of that.
These classes set up their listeners in OnEnable() and OnDisable().
If you want to use those methods you have to declare them as override and invoke the base ones to make sure the listeners are correctly set up:
Last updated
public class MySmartSO : AutoResetOnExitPlayMode
{
protected override void OnEnable()
{
base.OnEnable();
// This class' OnEnable code...
}
}