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
组件,它将如下(假设Container
是DiContainer
注入当前上下文的一个实例:
GameObject obj = _factory.Create(); // Creates from prefab
// instantiate and attach the component in once function
HasScore hasScore = Container.InstantiateComponent<HasScore>(obj);