Scriptable Object Installer - mariaheine/Zenject-But-Wiki GitHub Wiki
Another alternative to deriving from MonoInstaller or Installer when implementing your own installers, is to derive from the ScriptableObjectInstaller
class. This is most commonly used to store game settings. This approach has the following advantages:
- Any changes you make to the properties of the installer will persist after you stop play mode. This can be very useful when tweaking runtime parameters. For other installer types as well as any MonoBehaviour's in your scene, any changes to the inspector properties at runtime will be undone when play mode is stopped. However, there is a 'gotcha' to be aware of: Any changes to these settings in code will also be saved persistently (unlike with settings on MonoInstaller's). So if you go this route you should treat all settings objects as read-only to avoid this from happening.
- You can very easily swap out multiple instances of the same installer. For example, using the below example, you might have an instance of
GameSettingsInstaller
calledGameSettingsEasy
, and another one calledGameSettingsHard
, etc.
Example:
- Open Unity
- Right click somewhere in the Project tab and select
Create -> Zenject -> ScriptableObjectInstaller
- Name it GameSettingsInstaller
- Right click again in the same location
- Select the newly added menu item
Create -> Installers -> GameSettingsInstaller
- Following the approach to settings outlined here, you might then replace it with the following:
public class GameSettings : ScriptableObjectInstaller
{
public Player.Settings Player;
public SomethingElse.Settings SomethingElse;
// ... etc.
public override void InstallBindings()
{
Container.BindInstances(Player, SomethingElse, etc.);
}
}
public class Player : ITickable
{
readonly Settings _settings;
Vector3 _position;
public Player(Settings settings)
{
_settings = settings;
}
public void Tick()
{
_position += Vector3.forward * _settings.Speed;
}
[Serializable]
public class Settings
{
public float Speed;
}
}
- Now, you should be able to run your game and adjust the Speed value that is on the
GameSettingsInstaller
asset at runtime, and have that change saved permanently