首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Zenject动态添加组件

Zenject动态添加组件
EN

Stack Overflow用户
提问于 2016-09-15 22:59:21
回答 1查看 2.2K关注 0票数 1

如何将组件添加到游戏对象中?的正常路径

代码语言:javascript
复制
GameObject obj = _factory.Create(); // Creates from prefab

HasScore score = obj.AddComponent<HasScore>(); // attach the component

问题是HasScore组件没有经过IoC,因此没有注入依赖项。我的问题是如何添加组件?或者我如何让它通过IoC?我在文档里找不到这个,如果有人找到的话会很有价值的

代码语言:javascript
复制
[Inject]
public void Initialize(SomeSignal.Trigger trigger)
{
    _trigger = trigger;
    Debug.Log("[+] Injecting in HasScore...");
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-16 06:21:38

Unity Answers中的Bunny83回答了这个问题。答案就在Zenject的IInstantiator接口中。

代码语言:javascript
复制
// 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的一个实例:

代码语言:javascript
复制
GameObject obj = _factory.Create(); // Creates from prefab

// instantiate and attach the component in once function 
HasScore hasScore = Container.InstantiateComponent<HasScore>(obj); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39514334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档