1

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

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...");
}
4

1 回答 1

1

Unity Answers中的Bunny83回答了这个问题。答案IInstantiator在 Zenject 的界面中。

// 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组件,它将如下(假设ContainerDiContainer注入当前上下文的一个实例:

GameObject obj = _factory.Create(); // Creates from prefab

// instantiate and attach the component in once function 
HasScore hasScore = Container.InstantiateComponent<HasScore>(obj); 
于 2016-09-15T22:21:38.130 回答