我正在使用Zenject框架,并且希望为factory创建的类实例化gameObject。为此,我在GameInstaller中使用了类似的方法
Container.BindFactory<int,int,Hex, Hex.Factory().
FromComponentInNewPrefab(_settings.PlainHexPrefab[0]).
WithGameObjectName("Hex").
UnderTransformGroup("Zenject");`
它工作正常,但在_settings.PlainHexPrefab中,我有GameObjects集合,我需要根据Hex对象的属性选择其中之一依赖项。我该怎么办?
答案 0 :(得分:1)
以下三种可能对您有用的方法:
FromMethod
public class Hex : MonoBehaviour
{
public class Factory : PlaceholderFactory<int, int, Hex>
{
}
}
public class TestInstaller : MonoInstaller<TestInstaller>
{
public GameObject[] HexPrefabs;
public override void InstallBindings()
{
Container.BindFactory<int, int, Hex, Hex.Factory>().FromMethod(CreateHex);
}
Hex CreateHex(DiContainer _, int p1, int p2)
{
var prefab = HexPrefabs[Random.RandomRange(0, HexPrefabs.Count() -1)];
return Container.InstantiatePrefabForComponent<Hex>(prefab);
}
}
自定义工厂
public class HexFactory : IFactory<int, int, Hex>
{
readonly DiContainer _container;
readonly GameObject[] _prefabs;
public HexFactory(
GameObject[] prefabs,
DiContainer container)
{
_container = container;
_prefabs = prefabs;
}
public Hex Create(int p1, int p2)
{
var prefab = _prefabs[Random.RandomRange(0, _prefabs.Count() -1)];
return _container.InstantiatePrefabForComponent<Hex>(prefab);
}
}
public class TestInstaller : MonoInstaller<TestInstaller>
{
public GameObject[] HexPrefabs;
public override void InstallBindings()
{
Container.BindFactory<int, int, Hex, Hex.Factory>()
.FromIFactory(b => b.To<HexFactory>().AsSingle().WithArguments(HexPrefabs));
}
}
自定义工厂中的子工厂。这也具有每个预制工厂都应该“验证”的优点。
public class CustomHexFactory : IFactory<int, Hex>
{
readonly List<Hex.Factory> _subFactories;
public CustomHexFactory(List<Hex.Factory> subFactories)
{
_subFactories = subFactories;
}
public Hex Create(int p1)
{
return _subFactories[Random.RandomRange(0, _subFactories.Count() -1)].Create(p1);
}
}
public class TestInstaller : MonoInstaller<TestInstaller>
{
public GameObject[] HexPrefabs;
public override void InstallBindings()
{
foreach (var prefab in HexPrefabs)
{
Container.BindFactory<int, Hex, Hex.Factory>().FromComponentInNewPrefab(prefab)
.WhenInjectedInto<CustomHexFactory>();
}
Container.BindFactory<int, Hex, Hex.Factory>().FromFactory<CustomHexFactory>();
}
}