- Home /
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...");
}
Answer by Bunny83 · Sep 15, 2016 at 07:15 PM
I haven't really used Zenject so i can't tell you if this works. You most likely use a DIContainer somewhere in your code, right? You need access to it otherwise you can't handle the DI stuff.
The DIContainer has a method called InstantiateComponent<T>
where you pass a host gameobject and the method will add the specified component to the gameobject and does the injection afterwards,
As alternative you should also be able to run the injection manually by calling InjectExplicit
on your manually added component. In any ways you have to have access to the DIContainer. Usually the point of a factory is to fully create an object. It seems you want to modify the object after the creation. Maybe specify the things you want to add as parameters to Create?
We don't have enough information about your project to suggest anything.
Yep, DiContainer.InstantiateComponent
is exactly what I was looking for. I was looking in the wrong part for that function. Surprised these methods aren't listed in Zenject's Docs
Does InstantiateComponent ignore the bindings i made in installer?
No it'll honor the bindings you made in installer.
Answer by GilbertoBitt · Sep 16, 2016 at 11:32 AM
u should see if hasscore have dependencies like another component or a collider marked as trigger to work.. so.. i think that`s the problem u should add first the component that is neccessary to it work than u add it the hasScore.
ps: i don`t understand corretly your problem.. take a print of the erro.. add here some preview of the hasscore.. and what r the component of the obj?
I solved the issue my friend: HasScore hasScore = Container.InstantiateComponent<HasScore>(obj);
does exactly what I wanted
Your answer
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
Call compoent by name 2 Answers
Unity can't see any scripts 0 Answers
Unity can't see any scripts 0 Answers