0

I have a scene object with a Fruit test script whose interfaces I want to add to dependencies. To do this, I use the standard Zenject Binding script. However, this doesn't work. Please tell me how can I solve the problem?

enter image description here enter image description here

Maritim
  • 2,111
  • 4
  • 29
  • 59
Dirol
  • 1
  • 1

1 Answers1

0

You need to tell the container what to do with the depencencies. This is done with installers. There is a installing phase where you need to set the relation between the classes and the instances that need to be provided by the container. I recomend to read the documentation which is very good in this case.

For the case of MonoDehaviours you need to check the Scene bindings section in the documentation.

public class Foo : MonoBehaviour
{
}
    
public class GameInstaller : MonoInstaller
{
    public Foo foo;
    
    public override void InstallBindings()
    {
        Container.BindInstance(foo);
        Container.Bind<IInitializable>().To<GameRunner>().AsSingle();
    }
}
    
public class GameRunner : IInitializable
{
    readonly Foo _foo;

    public GameRunner(Foo foo)
    {
        _foo = foo;
    }
    
    public void Initialize()
    {
        // ...
    }
}

For your specific case:

public class Fruit: Monobehaviour. IInitializable, ITickable {
    public void Initialize() {

    }
    public void Tick() {

    }
}

public class GameInstaller : MonoInstaller
{
    public Fruit fruit;

    public override void InstallBindings()
    {
        Container.BindInstance(fruit);
        Container.Bind<IInitializable>().To<Fruit>().AsSingle();
        Container.Bind<ITickable>().To<Fruit>().AsSingle();
    }
}

Or you can also bind all the interfaces at once with:
Container.BindInterfacesTo<Fruit>().AsSingle();.

You need to add the GameInstaller in your SceneContext component for the installers to run along with the overridden InstallBindings() method.

Monolith
  • 1,067
  • 1
  • 13
  • 29
rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47