ã¯ããã«
ã©ãããåéã§ãã
ããã¯åéã²ã¨ã Advent Calendar 2024ã®1æ¥ç®ã®è¨äºã§ãã
ç¾å¨ãECSã§ã²ã¼ã ãä½ã£ã¦ã¿ã¦ããã®ã§ããããã®ããã¸ã§ã¯ãã§DIã£ã¦å°å ¥ã§ããªãã®ããªã¼ã¨æã調ã¹ãã¨ãããVContainerã対å¿ãã¦ããã¦ãããããªã®ã§ããã£ã¦ã¿ã¾ããã
DefaultWorldã«ãããDI
ãã¹ãç¨ã³ã¼ã
DIã§æ±ããããã«ããã«ã¯SystemBaseç¶æ¿ã§Systemãæ§ç¯ããå¿
è¦ãããã¾ãã
ISystemã§ã¯ãç¾ç¶ã§ããªãããã§ãã(ããããMonoBehaviorããæ±ããªãã®ã§)
public partial class SystemA : SystemBase { protected override void OnUpdate() { } public void TestMessage() { Debug.Log("SystemA"); } }
public partial class SystemB : SystemBase { [Inject] private SystemA _systemA; protected override void OnUpdate() { if (_systemA == null) return; _systemA.TestMessage(); } }
é常æã®DIã¨åæ§ã«[Inject]ã®Attributeãã¤ããã ãã§ããã«æµãè¾¼ã¾ãã¾ãã
LifetimeScope
LifetimeScopeãMonoBehaviorã®ã¨ãã¨åæ§ã以ä¸ã®ããã«ç°¡åã«è¨è¿°ã§ãã¾ãã
ãã®LifetimeScopeã¯ECS管çã§ã¯ãªãMonoBehaviorã®GameObjectã«ã¢ã¿ãããã¦ãã ããã
public class TestLifetimeScope : LifetimeScope { protected override void Configure(IContainerBuilder builder) { builder.RegisterSystemFromDefaultWorld<SystemA>(); builder.RegisterSystemFromDefaultWorld<SystemB>(); } }
ä¸è¨ã¯ä»¥ä¸ã®ããã«æ¸ãæãããã¨ãã§ãã¾ãã
builder.UseDefaultWorld(systems =>
{
systems.Add<SystemA>();
systems.Add<SystemB>();
});
CustomWorldã«ãããDI
èªåã§ä½ã£ãWorldã«é¢ãã¦DIãè¡ããã¨ãã§ãã¾ãã
ããã«ãã£ã¦Worldèªä½ãVContainerã«ç®¡çããããã¨ãã§ããããã§ãã
ãã¹ãç¨ã³ã¼ã
public partial class SystemC : SystemBase { readonly ServiceA serviceA; public SystemC(ServiceA serviceA) { this.serviceA = serviceA; } protected override void OnUpdate() { serviceA.TestMessage(); } }
public class ServiceA { public void TestMessage() { Debug.Log("ServiceA"); } }
ãã®ãããªé常ã®ã¯ã©ã¹ãSystemã«æµãããã«æ±ããã¨ããã¡ããã§ããã
LifetimeScope
以ä¸ã®ããã«è¨è¿°ãããã¨ã§ãWorldã®çæããç»é²ã¾ã§è¡ã£ã¦ãã¾ãã
builder.RegisterNewWorld("MyWorld", Lifetime.Scoped); builder.RegisterSystemIntoWorld<SystemC>("MyWorld"); builder.Register<ServiceA>(Lifetime.Singleton);