2016-09-15 4 views
1

Wie können Sie einem Spielobjekt eine Komponente hinzufügen? Der normale Weg derZenject Komponente dynamisch hinzufügen

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

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

Das Problem ist, dass HasScore Komponente nicht durch IoC wird daher die Abhängigkeiten injiziert werden nicht. Meine Frage ist, wie füge ich eine Komponente hinzu? Oder wie mache ich es durch IoC gehen? Ich konnte dies nicht in der Dokumentation finden, wenn jemand tut es wird viel

[Inject] 
public void Initialize(SomeSignal.Trigger trigger) 
{ 
    _trigger = trigger; 
    Debug.Log("[+] Injecting in HasScore..."); 
} 
+0

Wirklich gute Frage - leider habe ich keine Antwort. –

Antwort

0

Bunny83 in Unity Answers diese Frage beantwortet appriciated. Die Antwort ist in der IInstantiator Schnittstelle in 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); 

So nach, dass (Code Zenject der im Code sehr gut erklärt) Wenn ich es werde, um meine HasScore Komponente anhängen möchten wie folgt (Container Unter der Annahme, ist eine Instanz DiContainer in den aktuellen Kontext eingespritzt:

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

// instantiate and attach the component in once function 
HasScore hasScore = Container.InstantiateComponent<HasScore>(obj); 
Verwandte Themen