动态添加组件
本文关键字:组件 添加 动态 | 更新日期: 2023-09-27 18:07:05
如何在游戏对象中添加组件?
的法向路径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在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);