Zenject 动态添加组件
Zenject add component dynamically
如何向游戏对象添加组件?
的正常路径
GameObject obj = _factory.Create(); // Creates from prefab
HasScore score = obj.AddComponent<HasScore>(); // attach the component
问题是 HasScore
组件没有通过 IoC
因此没有注入依赖项。我的问题是如何添加组件?或者我如何让它通过 IoC
?我在文档中找不到这个,如果有人找到它会很受欢迎
[Inject]
public void Initialize(SomeSignal.Trigger trigger)
{
_trigger = trigger;
Debug.Log("[+] Injecting in HasScore...");
}
Bunny83 in Unity Answers 回答了这个问题。答案就在 Zenject 的 IInstantiator
界面。
// Add new component to existing game object and fill in its dependencies
// NOTE: Gameobject here is not a prefab prototype, it is an instance
TContract InstantiateComponent<TContract>(GameObject gameObject)
where TContract : Component;
TContract InstantiateComponent<TContract>(
GameObject gameObject, IEnumerable<object> extraArgs)
where TContract : Component;
Component InstantiateComponent(
Type componentType, GameObject gameObject);
Component InstantiateComponent(
Type componentType, GameObject gameObject, IEnumerable<object> extraArgs);
Component InstantiateComponentExplicit(
Type componentType, GameObject gameObject, List<TypeValuePair> extraArgs);
所以根据那个(Zenject 的代码在代码中有很好的解释)如果我想附加我的 HasScore
组件,它将如下所示(假设 Container
是 DiContainer
注入当前上下文:
GameObject obj = _factory.Create(); // Creates from prefab
// instantiate and attach the component in once function
HasScore hasScore = Container.InstantiateComponent<HasScore>(obj);
如何向游戏对象添加组件?
的正常路径GameObject obj = _factory.Create(); // Creates from prefab
HasScore score = obj.AddComponent<HasScore>(); // attach the component
问题是 HasScore
组件没有通过 IoC
因此没有注入依赖项。我的问题是如何添加组件?或者我如何让它通过 IoC
?我在文档中找不到这个,如果有人找到它会很受欢迎
[Inject]
public void Initialize(SomeSignal.Trigger trigger)
{
_trigger = trigger;
Debug.Log("[+] Injecting in HasScore...");
}
Bunny83 in Unity Answers 回答了这个问题。答案就在 Zenject 的 IInstantiator
界面。
// Add new component to existing game object and fill in its dependencies
// NOTE: Gameobject here is not a prefab prototype, it is an instance
TContract InstantiateComponent<TContract>(GameObject gameObject)
where TContract : Component;
TContract InstantiateComponent<TContract>(
GameObject gameObject, IEnumerable<object> extraArgs)
where TContract : Component;
Component InstantiateComponent(
Type componentType, GameObject gameObject);
Component InstantiateComponent(
Type componentType, GameObject gameObject, IEnumerable<object> extraArgs);
Component InstantiateComponentExplicit(
Type componentType, GameObject gameObject, List<TypeValuePair> extraArgs);
所以根据那个(Zenject 的代码在代码中有很好的解释)如果我想附加我的 HasScore
组件,它将如下所示(假设 Container
是 DiContainer
注入当前上下文:
GameObject obj = _factory.Create(); // Creates from prefab
// instantiate and attach the component in once function
HasScore hasScore = Container.InstantiateComponent<HasScore>(obj);