unity-game-enginezenject

Swap between multiple instances of ScriptableObjectInstaller procedurally


The documentation says that you can easily swap between multiple ScriptableObjectInstallers. And i think you do this by assigning needed ScriptableObjectInstaller of a same class in SceneContext. But what if i want to procedurally decide which instance of a settings to use? Do i need to somehow procedurally change a reference to my SettingsInstaller in a scene context before i inject that settings where i need them? If so, how do i do that?

For example, i have 2 instances of a same SettingsInstaller: SettingsEasy and SettingsHard. How do i switch between them programmatically before injection? If i would have 2 instances of that settings in a scene context, then it's gonna throw me an error like this:

ZenjectException: Found multiple matches when only one was expected for type 'MySettingsType' while building object with type 'ClassWhereIInjectingIt'.


Solution

  • One way to do this programmatically would be to install from a resource path like this:

    public class GameSettingsInstaller : ScriptableObjectInstaller<GameSettingsInstaller>
    {
        public override void InstallBindings()
        {
            // ...
        }
    }
    
    public class MainInstaller : MonoInstaller
    {
        public bool isHardDifficulty;
    
        public override void InstallBindings()
        {
            GameSettingsInstaller.InstallFromResource(isHardDifficulty ? "SettingsHard" : "SettingsEasy", Container);
        }
    }
    

    Here, I'm assuming they are placed in a path that looks like Resources/SettingsEasy and Resources/SettingsHard