Skip to content

Instantly share code, notes, and snippets.

@kennir
Forked from shayded-exe/EnemyFacade.Factory.cs
Created March 31, 2019 03:20
Show Gist options
  • Save kennir/adb0057f042712ef8d8d11cecfcac5e3 to your computer and use it in GitHub Desktop.
Save kennir/adb0057f042712ef8d8d11cecfcac5e3 to your computer and use it in GitHub Desktop.
Dynamic Zenject enemy prefab factory
public partial class EnemyFacade : MonoBehaviour
{
public class Factory : Factory<EnemyType, EnemyTunables, EnemyFacade> { }
}
public enum EnemyType
{
Red,
Green
}
public class GameInstaller : MonoInstaller
{
[SerializeField] private Settings settings = null;
public override void InstallBindings()
{
// Other bindings and stuff...
// Original factory for reference
//Container
// .BindFactory<EnemyTunables, EnemyFacade, EnemyFacade.Factory>()
// .FromSubContainerResolve()
// .ByPrefab<EnemyInstaller>(this.settings.EnemyFacadePrefab)
// .UnderGameObjectGroup("Enemies");
// New factory
Container
.BindFactory<EnemyType, EnemyTunables, EnemyFacade, EnemyFacade.Factory>()
.FromSubContainerResolve()
.ByMethod(CreateEnemy);
}
private void CreateEnemy(DiContainer subContainer, EnemyType type, EnemyTunables tunables)
{
subContainer
.Bind<EnemyFacade>()
.FromPrefab(this.settings.EnemyPrefabs.Single(p => p.Type == type).Prefab)
.UnderGameObjectGroup("Enemies");
subContainer.BindInstance(tunables, true).WhenInjectedInto<EnemyInstaller>();
}
[Serializable]
public class Settings
{
public List<EnemyPrefabMapping> EnemyPrefabs;
}
[Serializable]
public class EnemyPrefabMapping
{
public EnemyType Type;
public GameObject Prefab;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment