Service
Services: Outside sources and sinks for information e.g. Pathfinding, Leaderboards, Anti-Cheat, Social, Physics, even the game engine itself.
Service就是由外部提供的數據、信息以及操作來源,像是尋路、物理、日志等等。下面引用一下原文中的例子:一個簡單打出日志的功能。
簡單的實現
直接使用UnityEngine.Debug.Log()
。
直接調用目標功能函數雖然方便快捷,但是強耦合使代碼的維護性大大降低。一旦需要更換Log的實現方式或是增添什么功能,手動替換所有的Log是非常痛苦的事情。
解耦合的實現
- 使用Entiats的實現
制作LogComponent,用ReactiveSystem對LogSystem進行處理。
using UnityEngine;
using Entitias;
using System.Collections.Generic;
// debug message component
[Debug]
public sealed class DebugLogComponent : IComponent {
public string message;
}
// reactive system to handle messages
public class HandleDebugLogMessageSystem : ReactiveSystem<DebugEntity> {
// collector: Debug.Matcher.DebugLog
// filter: entity.hasDebugLog
public void Execute (List<DebugEntity> entities) {
foreach (var e in entities) {
Debug.Log(e.debugLog.message);
e.isDestroyed = true;
}
}
}
雖然這樣做解決了耦合度的問題(只有一行代碼需要替換),但在功能的實現上卻與Entitas緊緊掛在了一起,需要在這個System中引用其他第三方和引擎無關的類。
- 使用Interface的實現
設定ILogService,并且通過實現ILogService處理Log方法。
// the interface
public interface ILogService {
void LogMessage(string message);
}
// a class that implements the interface
using UnityEngine;
public class UnityDebugLogService : ILogService {
public void LogMessage(string message) {
Debug.Log(message);
}
}
// another class that does things differently but still implements the interface
using SomeJsonLib;
public class JsonLogService : ILogService {
string filepath;
string filename;
bool prettyPrint;
// etc...
public void LogMessage(string message) {
// open file
// parse contents
// write new contents
// close file
}
}
然后ILogService已經可以在外面正常使用,在Entitas中可以這樣用:
// the previous reactive system becomes
public class HandleDebugLogMessageSystem : ReactiveSystem<DebugEntity> {
ILogService _logService;
// contructor needs a new argument to get a reference to the log service
public HandleDebugLogMessageSystem(Contexts contexts, ILogService logService) {
// could be a UnityDebugLogService or a JsonLogService
_logService = logService;
}
// collector: Debug.Matcher.DebugLog
// filter: entity.hasDebugLog
public void Execute (List<DebugEntity> entities) {
foreach (var e in entities) {
_logService.LogMessage(e.DebugLog.message); // using the interface to call the method
e.isDestroyed = true;
}
}
}
上面代碼的ILogService是在Constructor中手動注入的,原文使用的方法是定義Services類,手動綁定并且在Entitas系統中注入所有的Services,這樣做非常麻煩,新增新的類以及外部使用接口方法的很不方便。在這個時候,Zenject能很好地解決我們的問題。
Zenject
Zenject 是一款為Unity3D設計的依賴注入的開源框架。
Git上面有非常詳盡的文檔介紹,我這邊簡單的說一下使用。
還是用上面的例子,我們依然使用Interface的實現方法,額外需要處理一下以下的組件
Installer
我們需要新建一個類集成MonoInstaller,在Binding方法中綁定ILogService,并且注冊成單例AsSingle()。
public interface IDebugService
{
void Log(string str);
}
public class UnityDebugService : IDebugService
{
public void Log(string str)
{
Debug.Log(obj);
}
}
public class ServicesInstaller : MonoInstaller
{
public override void InstallBindings()
{
// Unity Debug
Container.Bind<IDebugService>().To<UnityDebugService>().AsSingle();
}
}
Context
我們需要在場景中增加一個SceneContext(還有Project/Decorator的Context 官方文檔中有注明),將剛才增加的Installer掛載到Scene Context的GameObject上,并且在SceneContext上加入該Installer。
完成以上的步驟后,只要從Zenject中Resolve出來,Zenject的自動注入就會生效了。Zenject支持多種注入方式,這里推薦使用構造器注入以及方法注入。
構造器注入
public clas Test
{
private ILogService _logService;
public Test(ILogService logService)
{
_logService = logService;
}
}
那么在Entitas中怎么Resolve所有的系統呢?這里需要用到在Installer種用到反射獲取所有的ISystem來進行綁定。
public class SystemsInstaller : MonoInstaller
{
public string[] SystemNamepsaces;
public override void InstallBindings()
{
// Resolve contexts
Container.Bind<Contexts>().FromInstance(Contexts.sharedInstance).AsSingle().NonLazy();
Container.Bind<string[]>().WithId("SystemNamepsaces").FromInstance(SystemNamepsaces).AsSingle();
// Resolve all systems
for (var i = 0; i < SystemNamepsaces.Length; i++)
{
var nameSpace = SystemNamepsaces[i];
Container.Bind<ISystem>().WithId(nameSpace).To(x => x.AllTypes()
.DerivingFrom<ISystem>().InNamespaces(nameSpace)).AsSingle();
}
Container.Bind<GameController>().FromNewComponentOnNewGameObject()
.AsSingle().NonLazy();
}
}
同時在GameController中用DiContainer Resolve所有的System(GameController是Entitas的啟動入口)。
public class GameController : MonoBehaviour
{
private DiContainer _container;
[Inject(Id = "SystemNamepsaces")]
private string[] _systemNamespaces;
[SerializeField]
public Systems Systems = new Systems();
...
private void SetupAllBindingSystems()
{
var autoBindingFeature = new Feature("Auto Binding Features");
for (var i = 0; i < _systemNamespaces.Length; i++)
{
var nameSpace = _systemNamespaces[i];
var allSystems = _container.ResolveIdAll<ISystem>(nameSpace);
var featureName = nameSpace.Split('.').LastOrDefault() + " Systems";
var feature = new Feature(featureName);
allSystems.ForEach(x => feature.Add(x));
autoBindingFeature.Add(feature);
}
Systems.Add(autoBindingFeature);
}
...
}
這樣我們就完成了所有System的自動注入,我們只需要在Inspector上加入系統的Namespace就能自動注入該命名空間的所有系統了。