Arijoon
Arijoon

Reputation: 2300

Zenject add component dynamically

How can you add a component to a gameobject? The normal path of

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

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

The problem is that HasScore component is not going through IoC hence the dependencies are not injected. My question is how do I add a component? Or how do I make it go through IoC ? I couldn't find this in the docs, if anyone does it'll be much appriciated

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

Upvotes: 1

Views: 4201

Answers (1)

Arijoon
Arijoon

Reputation: 2300

Bunny83 in Unity Answers answered this question. The answer is in the IInstantiator interface 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 according to that (Zenject's code is very well explained in the code) If I want to attach my HasScore component it'll be as follows (Assuming Container is an instance of DiContainer injected into the current context:

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

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

Upvotes: 2

Related Questions