Zenject: Non-MonoBehaviour Classes

yoonsang lee·2022년 5월 29일
0

ITickable

In order to avoid the cost of inheriting MonoBehaviour of class, then you can stick with ITickable.Tick()

public class Ship : ITickable {
    public void Tick() {
        // Perform per frame tasks
    }
}

and to hook it up in an installer,

Container.Bind<ITickable>().To<Ship>().AsSingle();

BindInterfacesTo and BindInterfacesAndSelfTo

It is shorten of Interface binding for implementing ITickable, IInitializable and IDisposable

//from
Container.Bind(typeof(Foo), typeof(IInitializable), typeof(IDisposable)).To<Logger>().AsSingle();

// into
Container.BindInterfacesAndSelfTo<Foo>().AsSingle();

// in case of only bind the interfaces,
Container.BindInterfacesTo<Foo>().AsSingle();

IInitializable

Rather than construct the class, you better implement IInitializable interface to fulfill it

Container.Bind<IInitializable>().To<Foo>().AsSingle();
  • Execution Order is like
    the constructors for the initial object graph are called during Unity's Awake event, and that the IInitializable.Initialize methods are called immediately on Unity's Start event.

  • Unity's own recommendations, which suggest that the Awake phase be used to set up object references, and the Start phase be used for more involved initialization logic.


IDisposable

If you have external resources that you want to clean up when the app closes, the scene changes, or for whatever reason the context object is destroyed, you can declare your class as IDisposable

public class Logger : IInitializable, IDisposable {
    FileStream _outStream;

    public void Initialize() {
        _outStream = File.Open("log.txt", FileMode.Open);
    }

    public void Log(string msg) {
        _outStream.WriteLine(msg);
    }

    public void Dispose() {
        _outStream.Close();
    }
}
  • This works because when the scene changes or your unity application is closed, the unity event OnDestroy() is called on all MonoBehaviours, including the SceneContext class, which then triggers Dispose() on all objects that are bound to IDisposable.
profile
Unity3D Freelancer Programmer + React

0개의 댓글