Procházet zdrojové kódy

EventSystem ObjectPool CodeLoader IdGenerater等等单例由Game统一管理,使用Game.AddSingleton注册

tanghai před 3 roky
rodič
revize
22b70461a5
78 změnil soubory, kde provedl 536 přidání a 497 odebrání
  1. 2 21
      DotNet/App/CodeLoader.cs
  2. 2 2
      DotNet/App/ConfigLoader.cs
  3. 12 10
      DotNet/App/Init.cs
  4. 1 1
      DotNet/App/ReloadDllConsoleHandler.cs
  5. 17 20
      DotNet/Tool/Init.cs
  6. 0 3
      Excel/Json/c/StartMachineConfig.txt
  7. 0 4
      Excel/Json/c/StartProcessConfig.txt
  8. 0 9
      Excel/Json/c/StartSceneConfig.txt
  9. 0 4
      Excel/Json/c/StartZoneConfig.txt
  10. 0 3
      Excel/Json/s/StartMachineConfig.txt
  11. 0 3
      Excel/Json/s/StartProcessConfig.txt
  12. 0 14
      Excel/Json/s/StartSceneConfig.txt
  13. 0 5
      Excel/Json/s/StartZoneConfig.txt
  14. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Login/EnterMapHelper.cs
  15. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Login/LoginHelper.cs
  16. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Ping/PingComponentSystem.cs
  17. 2 2
      Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Scene/SceneChangeHelper.cs
  18. 2 2
      Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Scene/SceneFactory.cs
  19. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Unit/UnitFactory.cs
  20. 5 5
      Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/EntryEvent2_InitServer.cs
  21. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Gate/SessionPlayerComponentSystem.cs
  22. 2 2
      Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Helper/InnerMessageDispatcherHelper.cs
  23. 5 5
      Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Helper/SessionStreamDispatcherServerInner.cs
  24. 2 2
      Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Robot/Console/CreateRobotConsoleHandler.cs
  25. 4 4
      Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Watcher/WatcherHelper.cs
  26. 2 2
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/AOI/AOIEntitySystem.cs
  27. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/Actor/ActorMessageDispatcherComponentSystem.cs
  28. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/ActorLocation/ActorLocationSenderComponentSystem.cs
  29. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/Console/ReloadConfigConsoleHandler.cs
  30. 3 0
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/Http/HttpComponentSystem.cs
  31. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/MessageInner/NetInnerComponentSystem.cs
  32. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/RobotCase/RobotCaseDispatcherComponentSystem.cs
  33. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Share/Module/AI/AIDispatcherComponentSystem.cs
  34. 5 5
      Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Config/ConfigComponentSystem.cs
  35. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Message/MessageDispatcherComponentSystem.cs
  36. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Message/NetKcpComponentSystem.cs
  37. 2 2
      Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Move/MoveComponentSystem.cs
  38. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Recast/NavmeshComponentSystem.cs
  39. 1 1
      Unity/Assets/Scripts/Codes/HotfixView/Client/Demo/EntryEvent3_InitClient.cs
  40. 1 1
      Unity/Assets/Scripts/Codes/HotfixView/Client/Demo/Opera/OperaComponentSystem.cs
  41. 1 1
      Unity/Assets/Scripts/Codes/HotfixView/Client/Module/UI/UIEventComponentSystem.cs
  42. 1 1
      Unity/Assets/Scripts/Codes/Model/Server/Module/MessageInner/NetInnerComponent.cs
  43. 4 4
      Unity/Assets/Scripts/Codes/Model/Share/Entry.cs
  44. 1 1
      Unity/Assets/Scripts/Codes/Model/Share/Module/CoroutineLock/CoroutineLockComponent.cs
  45. 7 3
      Unity/Assets/Scripts/Codes/Model/Share/Module/Log/NLogger.cs
  46. 2 2
      Unity/Assets/Scripts/Codes/Model/Share/Module/Message/OpcodeHelper.cs
  47. 2 2
      Unity/Assets/Scripts/Codes/Model/Share/Module/Message/OpcodeTypeComponent.cs
  48. 1 1
      Unity/Assets/Scripts/Codes/Model/Share/Module/Numeric/NumericComponent.cs
  49. 1 1
      Unity/Assets/Scripts/Codes/Model/Share/Module/Numeric/NumericWatcherComponent.cs
  50. 2 2
      Unity/Assets/Scripts/Codes/Model/Share/Module/Timer/TimerComponent.cs
  51. 2 2
      Unity/Assets/Scripts/Codes/Model/Share/Module/Unit/Unit.cs
  52. 1 1
      Unity/Assets/Scripts/Codes/ModelView/Client/Demo/Config/ConfigLoader.cs
  53. 43 27
      Unity/Assets/Scripts/Core/Entity/Game.cs
  54. 18 0
      Unity/Assets/Scripts/Core/Entity/Root.cs
  55. 1 1
      Unity/Assets/Scripts/Core/Entity/Root.cs.meta
  56. 2 2
      Unity/Assets/Scripts/Core/HashSetComponent.cs
  57. 2 2
      Unity/Assets/Scripts/Core/ListComponent.cs
  58. 14 87
      Unity/Assets/Scripts/Core/Log/Log.cs
  59. 161 0
      Unity/Assets/Scripts/Core/Log/Logger.cs
  60. 1 1
      Unity/Assets/Scripts/Core/Log/Logger.cs.meta
  61. 0 31
      Unity/Assets/Scripts/Core/MongoHelper.cs
  62. 44 0
      Unity/Assets/Scripts/Core/MongoRegister.cs
  63. 11 0
      Unity/Assets/Scripts/Core/MongoRegister.cs.meta
  64. 0 48
      Unity/Assets/Scripts/Core/MonoPool.cs
  65. 13 13
      Unity/Assets/Scripts/Core/Object/Entity.cs
  66. 2 22
      Unity/Assets/Scripts/Core/Object/EventSystem.cs
  67. 6 14
      Unity/Assets/Scripts/Core/Object/IdGenerater.cs
  68. 11 17
      Unity/Assets/Scripts/Core/Object/ObjectPool.cs
  69. 8 10
      Unity/Assets/Scripts/Core/Options.cs
  70. 0 10
      Unity/Assets/Scripts/Core/PoolHelper.cs
  71. 43 0
      Unity/Assets/Scripts/Core/Singleton.cs
  72. 11 0
      Unity/Assets/Scripts/Core/Singleton.cs.meta
  73. 6 11
      Unity/Assets/Scripts/Core/TimeInfo.cs
  74. 5 24
      Unity/Assets/Scripts/Mono/CodeLoader.cs
  75. 17 6
      Unity/Assets/Scripts/Mono/MonoBehaviour/Init.cs
  76. 3 3
      Unity/Assets/Scripts/ThirdParty/ETTask/ETTask.cs
  77. 2 0
      Unity/Packages/manifest.json
  78. 3 1
      Unity/ProjectSettings/EditorSettings.asset

+ 2 - 21
DotNet/App/CodeLoader.cs

@@ -6,30 +6,11 @@ using System.Runtime.Loader;
 
 namespace ET
 {
-    public class CodeLoader: IDisposable
+    public class CodeLoader: Singleton<CodeLoader>
     {
         private AssemblyLoadContext assemblyLoadContext;
         
         private Assembly hotfix;
-        
-        private static CodeLoader instance;
-		
-        public static CodeLoader Instance 
-        {
-            get
-            {
-                return instance ??= new CodeLoader();
-            }
-        }
-
-        private CodeLoader()
-        {
-        }
-		
-        public void Dispose()
-        {
-            instance = null;
-        }
 
         public void Start()
         {
@@ -49,7 +30,7 @@ namespace ET
             
             Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof(Init).Assembly, typeof (Game).Assembly, typeof(Entry).Assembly, this.hotfix);
 			
-            Game.EventSystem.Add(types);
+            EventSystem.Instance.Add(types);
         }
     }
 }

+ 2 - 2
DotNet/App/ConfigLoader.cs

@@ -17,13 +17,13 @@ namespace ET
                 "StartSceneConfigCategory", 
                 "StartZoneConfigCategory",
             };
-            HashSet<Type> configTypes = Game.EventSystem.GetTypes(typeof (ConfigAttribute));
+            HashSet<Type> configTypes = EventSystem.Instance.GetTypes(typeof (ConfigAttribute));
             foreach (Type configType in configTypes)
             {
                 string configFilePath;
                 if (startConfigs.Contains(configType.Name))
                 {
-                    configFilePath = $"../Config/{Game.Options.StartConfig}/{configType.Name}.bytes";    
+                    configFilePath = $"../Config/{Options.Instance.StartConfig}/{configType.Name}.bytes";    
                 }
                 else
                 {

+ 12 - 10
DotNet/App/Init.cs

@@ -18,25 +18,27 @@ namespace ET
 				
 				// 异步方法全部会回掉到主线程
 				SynchronizationContext.SetSynchronizationContext(ThreadSynchronizationContext.Instance);
+
 				
 				// 命令行参数
 				Options options = null;
 				Parser.Default.ParseArguments<Options>(args)
-						.WithNotParsed(error => throw new Exception($"命令行格式错误!"))
+						.WithNotParsed(error => throw new Exception($"命令行格式错误! {error}"))
 						.WithParsed(o => { options = o; });
-				Options.Instance = options;
-				
-				LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("../Config/NLog/NLog.config");
-				LogManager.Configuration.Variables["appIdFormat"] = $"{Game.Options.Process:000000}";
-				LogManager.Configuration.Variables["currentDir"] = Environment.CurrentDirectory;
 				
-				Game.ILog = new NLogger(Game.Options.AppType.ToString());
+				Game.AddSingleton(options);
+				Game.AddSingleton<TimeInfo>();
+				Game.AddSingleton<Logger>().ILog = new NLogger(Options.Instance.AppType.ToString(), Options.Instance.Process, "../Config/NLog/NLog.config");
+				Game.AddSingleton<ObjectPool>();
+				Game.AddSingleton<IdGenerater>();
+				Game.AddSingleton<EventSystem>();
+				Game.AddSingleton<Root>();
 				
 				ETTask.ExceptionHandler += Log.Error;
-			
-				CodeLoader.Instance.Start();
 
-				Log.Console($"app start: {Game.Scene.Id} options: {JsonHelper.ToJson(Game.Options)} ");
+				Game.AddSingleton<CodeLoader>().Start();
+
+				Log.Console($"app start: {Game.Scene.Id} options: {JsonHelper.ToJson(Options.Instance)} ");
 
 				while (true)
 				{

+ 1 - 1
DotNet/App/ReloadDllConsoleHandler.cs

@@ -14,7 +14,7 @@ namespace ET
                     
                     CodeLoader.Instance.LoadHotfix();
                     
-                    Game.EventSystem.Load();
+                    EventSystem.Instance.Load();
                     break;
             }
             

+ 17 - 20
DotNet/Tool/Init.cs

@@ -2,7 +2,6 @@
 using System.Collections.Generic;
 using System.Threading;
 using CommandLine;
-using NLog;
 
 namespace ET.Server
 {
@@ -14,8 +13,6 @@ namespace ET.Server
             {
                 Log.Error(e.ExceptionObject.ToString());
             };
-
-            ETTask.ExceptionHandler += Log.Error;
             
             // 异步方法全部会回掉到主线程
             SynchronizationContext.SetSynchronizationContext(ThreadSynchronizationContext.Instance);
@@ -28,37 +25,37 @@ namespace ET.Server
                 // 命令行参数
                 Options options = null;
                 Parser.Default.ParseArguments<Options>(args)
-                    .WithNotParsed(error => throw new Exception($"命令行格式错误!"))
-                    .WithParsed(o => { options = o; });
-                Options.Instance = options;
-				
-                LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("../Config/NLog/NLog.config");
-                LogManager.Configuration.Variables["appIdFormat"] = $"{Game.Options.Process:000000}";
-                LogManager.Configuration.Variables["currentDir"] = Environment.CurrentDirectory;
+                        .WithNotParsed(error => throw new Exception($"命令行格式错误! {error}"))
+                        .WithParsed(o => { options = o; });
 				
-                Game.ILog = new NLogger(Game.Options.AppType.ToString());
-				
-                ETTask.ExceptionHandler += Log.Error;
+                Game.AddSingleton(options);
+                Game.AddSingleton<TimeInfo>();
+                Game.AddSingleton<Logger>().ILog = new NLogger(Options.Instance.AppType.ToString(), Options.Instance.Process, "../Config/NLog/NLog.config");
+                Game.AddSingleton<ObjectPool>();
+                Game.AddSingleton<IdGenerater>();
+                Game.AddSingleton<EventSystem>();
+                Game.AddSingleton<Root>();
                 
+                ETTask.ExceptionHandler += Log.Error;
+
                 Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof (Game).Assembly);
-                    
-                Game.EventSystem.Add(types);
-                
-                MongoHelper.Register(Game.EventSystem.GetTypes());
+                EventSystem.Instance.Add(types);
+
+                MongoRegister.Init();
 				
                 Log.Info($"server start........................ {Game.Scene.Id}");
 				
-                switch (Game.Options.AppType)
+                switch (Options.Instance.AppType)
                 {
                     case AppType.ExcelExporter:
                     {
-                        Game.Options.Console = 1;
+                        Options.Instance.Console = 1;
                         ExcelExporter.Export();
                         return 0;
                     }
                     case AppType.Proto2CS:
                     {
-                        Game.Options.Console = 1;
+                        Options.Instance.Console = 1;
                         Proto2CS.Export();
                         return 0;
                     }

+ 0 - 3
Excel/Json/c/StartMachineConfig.txt

@@ -1,3 +0,0 @@
-{"list":[
-{"_t":"StartMachineConfig","_id":1,"InnerIP":"127.0.0.1","OuterIP":"127.0.0.1","WatcherPort":"10000"},
-]}

+ 0 - 4
Excel/Json/c/StartProcessConfig.txt

@@ -1,4 +0,0 @@
-{"list":[
-{"_t":"StartProcessConfig","_id":1,"MachineId":1,"InnerPort":20001},
-{"_t":"StartProcessConfig","_id":2,"MachineId":1,"InnerPort":20002},
-]}

+ 0 - 9
Excel/Json/c/StartSceneConfig.txt

@@ -1,9 +0,0 @@
-{"list":[
-{"_t":"StartSceneConfig","_id":1,"Process":1,"Zone":1,"SceneType":"Realm","Name":"Realm","OuterPort":10002},
-{"_t":"StartSceneConfig","_id":2,"Process":1,"Zone":1,"SceneType":"Gate","Name":"Gate1","OuterPort":10003},
-{"_t":"StartSceneConfig","_id":3,"Process":1,"Zone":1,"SceneType":"Gate","Name":"Gate2","OuterPort":10004},
-{"_t":"StartSceneConfig","_id":4,"Process":1,"Zone":1,"SceneType":"Location","Name":"Location","OuterPort":0},
-{"_t":"StartSceneConfig","_id":5,"Process":1,"Zone":1,"SceneType":"Map","Name":"Map1","OuterPort":0},
-{"_t":"StartSceneConfig","_id":6,"Process":1,"Zone":1,"SceneType":"Map","Name":"Map2","OuterPort":0},
-{"_t":"StartSceneConfig","_id":200,"Process":1,"Zone":2,"SceneType":"Robot","Name":"Robot01","OuterPort":0},
-]}

+ 0 - 4
Excel/Json/c/StartZoneConfig.txt

@@ -1,4 +0,0 @@
-{"list":[
-{"_t":"StartZoneConfig","_id":1,"DBConnection":"mongodb://127.0.0.1","DBName":"ET1"},
-{"_t":"StartZoneConfig","_id":2,"DBConnection":"mongodb://127.0.0.1","DBName":"ET2"},
-]}

+ 0 - 3
Excel/Json/s/StartMachineConfig.txt

@@ -1,3 +0,0 @@
-{"list":[
-{"_t":"StartMachineConfig","_id":1,"InnerIP":"127.0.0.1","OuterIP":"127.0.0.1","WatcherPort":"10000"},
-]}

+ 0 - 3
Excel/Json/s/StartProcessConfig.txt

@@ -1,3 +0,0 @@
-{"list":[
-{"_t":"StartProcessConfig","_id":1,"MachineId":1,"InnerPort":20001},
-]}

+ 0 - 14
Excel/Json/s/StartSceneConfig.txt

@@ -1,14 +0,0 @@
-{"list":[
-{"_t":"StartSceneConfig","_id":1,"Process":1,"Zone":1,"SceneType":"Realm","Name":"Realm","OuterPort":10002},
-{"_t":"StartSceneConfig","_id":2,"Process":1,"Zone":1,"SceneType":"Gate","Name":"Gate1","OuterPort":10003},
-{"_t":"StartSceneConfig","_id":3,"Process":1,"Zone":1,"SceneType":"Gate","Name":"Gate2","OuterPort":10004},
-{"_t":"StartSceneConfig","_id":4,"Process":1,"Zone":1,"SceneType":"Location","Name":"Location","OuterPort":0},
-{"_t":"StartSceneConfig","_id":5,"Process":1,"Zone":1,"SceneType":"Map","Name":"Map1","OuterPort":0},
-{"_t":"StartSceneConfig","_id":6,"Process":1,"Zone":1,"SceneType":"Map","Name":"Map2","OuterPort":0},
-{"_t":"StartSceneConfig","_id":200,"Process":1,"Zone":2,"SceneType":"Robot","Name":"Robot01","OuterPort":0},
-{"_t":"StartSceneConfig","_id":300,"Process":1,"Zone":3,"SceneType":"RouterManager","Name":"RouterManager","OuterPort":10300},
-{"_t":"StartSceneConfig","_id":301,"Process":1,"Zone":3,"SceneType":"Router","Name":"Router01","OuterPort":10301},
-{"_t":"StartSceneConfig","_id":302,"Process":1,"Zone":3,"SceneType":"Router","Name":"Router02","OuterPort":10302},
-{"_t":"StartSceneConfig","_id":303,"Process":1,"Zone":3,"SceneType":"Router","Name":"Router03","OuterPort":10303},
-{"_t":"StartSceneConfig","_id":304,"Process":1,"Zone":3,"SceneType":"Router","Name":"Router04","OuterPort":10304},
-]}

+ 0 - 5
Excel/Json/s/StartZoneConfig.txt

@@ -1,5 +0,0 @@
-{"list":[
-{"_t":"StartZoneConfig","_id":1,"DBConnection":"mongodb://127.0.0.1","DBName":"ET1"},
-{"_t":"StartZoneConfig","_id":2,"DBConnection":"","DBName":""},
-{"_t":"StartZoneConfig","_id":3,"DBConnection":"","DBName":""},
-]}

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Login/EnterMapHelper.cs

@@ -15,7 +15,7 @@ namespace ET.Client
                 // 等待场景切换完成
                 await clientScene.GetComponent<ObjectWait>().Wait<WaitType.Wait_SceneChangeFinish>();
                 
-                Game.EventSystem.Publish(clientScene, new EventType.EnterMapFinish());
+                EventSystem.Instance.Publish(clientScene, new EventType.EnterMapFinish());
             }
             catch (Exception e)
             {

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Login/LoginHelper.cs

@@ -46,7 +46,7 @@ namespace ET.Client
 
                 Log.Debug("登陆gate成功!");
 
-                await Game.EventSystem.PublishAsync(clientScene, new EventType.LoginFinish());
+                await EventSystem.Instance.PublishAsync(clientScene, new EventType.LoginFinish());
             }
             catch (Exception e)
             {

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Ping/PingComponentSystem.cs

@@ -35,7 +35,7 @@ namespace ET.Client
                     long time2 = TimeHelper.ClientNow();
                     self.Ping = time2 - time1;
                     
-                    Game.TimeInfo.ServerMinusClientTime = response.Time + (time2 - time1) / 2 - time2;
+                    TimeInfo.Instance.ServerMinusClientTime = response.Time + (time2 - time1) / 2 - time2;
 
                     await TimerComponent.Instance.WaitAsync(2000);
                 }

+ 2 - 2
Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Scene/SceneChangeHelper.cs

@@ -13,7 +13,7 @@
             UnitComponent unitComponent = currentScene.AddComponent<UnitComponent>();
          
             // 可以订阅这个事件中创建Loading界面
-            Game.EventSystem.Publish(clientScene, new EventType.SceneChangeStart());
+            EventSystem.Instance.Publish(clientScene, new EventType.SceneChangeStart());
 
             // 等待CreateMyUnit的消息
             WaitType.Wait_CreateMyUnit waitCreateMyUnit = await clientScene.GetComponent<ObjectWait>().Wait<WaitType.Wait_CreateMyUnit>();
@@ -23,7 +23,7 @@
             
             clientScene.RemoveComponent<AIComponent>();
             
-            Game.EventSystem.Publish(currentScene, new EventType.SceneChangeFinish());
+            EventSystem.Instance.Publish(currentScene, new EventType.SceneChangeFinish());
 
             // 通知等待场景切换的协程
             clientScene.GetComponent<ObjectWait>().Notify(new WaitType.Wait_SceneChangeFinish());

+ 2 - 2
Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Scene/SceneFactory.cs

@@ -15,7 +15,7 @@ namespace ET.Client
             clientScene.AddComponent<ObjectWait>();
             clientScene.AddComponent<PlayerComponent>();
             
-            Game.EventSystem.Publish(clientScene, new EventType.AfterCreateClientScene());
+            EventSystem.Instance.Publish(clientScene, new EventType.AfterCreateClientScene());
             return clientScene;
         }
         
@@ -24,7 +24,7 @@ namespace ET.Client
             Scene currentScene = EntitySceneFactory.CreateScene(id, IdGenerater.Instance.GenerateInstanceId(), zone, SceneType.Current, name, currentScenesComponent);
             currentScenesComponent.Scene = currentScene;
             
-            Game.EventSystem.Publish(currentScene, new EventType.AfterCreateCurrentScene());
+            EventSystem.Instance.Publish(currentScene, new EventType.AfterCreateCurrentScene());
             return currentScene;
         }
         

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Unit/UnitFactory.cs

@@ -41,7 +41,7 @@ namespace ET.Client
 
 	        unit.AddComponent<XunLuoPathComponent>();
 	        
-	        Game.EventSystem.Publish(unit.DomainScene(), new EventType.AfterUnitCreate() {Unit = unit});
+	        EventSystem.Instance.Publish(unit.DomainScene(), new EventType.AfterUnitCreate() {Unit = unit});
             return unit;
         }
     }

+ 5 - 5
Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/EntryEvent2_InitServer.cs

@@ -20,14 +20,14 @@ namespace ET.Server
 
             Game.Scene.AddComponent<NavmeshComponent>();
 
-            StartProcessConfig processConfig = StartProcessConfigCategory.Instance.Get(Game.Options.Process);
-            switch (Game.Options.AppType)
+            StartProcessConfig processConfig = StartProcessConfigCategory.Instance.Get(Options.Instance.Process);
+            switch (Options.Instance.AppType)
             {
                 case AppType.Server:
                 {
                     Game.Scene.AddComponent<NetInnerComponent, IPEndPoint, int>(processConfig.InnerIPPort, SessionStreamCallbackId.SessionStreamDispatcherServerInner);
 
-                    var processScenes = StartSceneConfigCategory.Instance.GetByProcess(Game.Options.Process);
+                    var processScenes = StartSceneConfigCategory.Instance.GetByProcess(Options.Instance.Process);
                     foreach (StartSceneConfig startConfig in processScenes)
                     {
                         await SceneFactory.Create(Game.Scene, startConfig.Id, startConfig.InstanceId, startConfig.Zone, startConfig.Name,
@@ -40,7 +40,7 @@ namespace ET.Server
                 {
                     StartMachineConfig startMachineConfig = WatcherHelper.GetThisMachineConfig();
                     WatcherComponent watcherComponent = Game.Scene.AddComponent<WatcherComponent>();
-                    watcherComponent.Start(Game.Options.CreateScenes);
+                    watcherComponent.Start(Options.Instance.CreateScenes);
                     Game.Scene.AddComponent<NetInnerComponent, IPEndPoint, int>(NetworkHelper.ToIPEndPoint($"{startMachineConfig.InnerIP}:{startMachineConfig.WatcherPort}"), SessionStreamCallbackId.SessionStreamDispatcherServerInner);
                     break;
                 }
@@ -48,7 +48,7 @@ namespace ET.Server
                     break;
             }
 
-            if (Game.Options.Console == 1)
+            if (Options.Instance.Console == 1)
             {
                 Game.Scene.AddComponent<ConsoleComponent>();
             }

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Gate/SessionPlayerComponentSystem.cs

@@ -9,7 +9,7 @@ namespace ET.Server
 			protected override void Destroy(SessionPlayerComponent self)
 			{
 				// 发送断线消息
-				ActorLocationSenderComponent.Instance.Send(self.PlayerId, new G2M_SessionDisconnect());
+				ActorLocationSenderComponent.Instance?.Send(self.PlayerId, new G2M_SessionDisconnect());
 				self.DomainScene().GetComponent<PlayerComponent>()?.Remove(self.PlayerId);
 			}
 		}

+ 2 - 2
Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Helper/InnerMessageDispatcherHelper.cs

@@ -13,7 +13,7 @@ namespace ET.Server
         [EnableAccessEntiyChild]
         public static void HandleIActorRequest(ushort opcode, long actorId, IActorRequest iActorRequest, Action<IActorResponse> reply)
         {
-            Entity entity = Game.EventSystem.Get(actorId);
+            Entity entity = EventSystem.Instance.Get(actorId);
             if (entity == null)
             {
                 FailResponse(iActorRequest, ErrorCore.ERR_NotFoundActor, reply);
@@ -69,7 +69,7 @@ namespace ET.Server
         {
             OpcodeHelper.LogMsg(opcode, actorId, iActorMessage);
 
-            Entity entity = Game.EventSystem.Get(actorId);
+            Entity entity = EventSystem.Instance.Get(actorId);
             if (entity == null)
             {
                 Log.Error($"not found actor: {actorId} {iActorMessage}");

+ 5 - 5
Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Helper/SessionStreamDispatcherServerInner.cs

@@ -22,11 +22,11 @@ namespace ET.Server
                 if (OpcodeTypeComponent.Instance.IsOutrActorMessage(opcode))
                 {
                     InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
-                    instanceIdStruct.Process = Game.Options.Process;
+                    instanceIdStruct.Process = Options.Instance.Process;
                     long realActorId = instanceIdStruct.ToLong();
                     
                     
-                    Entity entity = Game.EventSystem.Get(realActorId);
+                    Entity entity = EventSystem.Instance.Get(realActorId);
                     if (entity == null)
                     {
                         type = OpcodeTypeComponent.Instance.GetType(opcode);
@@ -62,7 +62,7 @@ namespace ET.Server
                     {
                         InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                         int fromProcess = instanceIdStruct.Process;
-                        instanceIdStruct.Process = Game.Options.Process;
+                        instanceIdStruct.Process = Options.Instance.Process;
                         long realActorId = instanceIdStruct.ToLong();
                         
                         void Reply(IActorResponse response)
@@ -78,7 +78,7 @@ namespace ET.Server
                     case IActorResponse iActorResponse:
                     {
                         InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
-                        instanceIdStruct.Process = Game.Options.Process;
+                        instanceIdStruct.Process = Options.Instance.Process;
                         long realActorId = instanceIdStruct.ToLong();
                         InnerMessageDispatcherHelper.HandleIActorResponse(opcode, realActorId, iActorResponse);
                         return;
@@ -86,7 +86,7 @@ namespace ET.Server
                     case IActorMessage iactorMessage:
                     {
                         InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
-                        instanceIdStruct.Process = Game.Options.Process;
+                        instanceIdStruct.Process = Options.Instance.Process;
                         long realActorId = instanceIdStruct.ToLong();
                         InnerMessageDispatcherHelper.HandleIActorMessage(opcode, realActorId, iactorMessage);
                         return;

+ 2 - 2
Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Robot/Console/CreateRobotConsoleHandler.cs

@@ -26,7 +26,7 @@ namespace ET.Server
                         List<StartSceneConfig> robotSceneConfigs = StartSceneConfigCategory.Instance.Robots;
                         foreach (StartSceneConfig robotSceneConfig in robotSceneConfigs)
                         {
-                            if (robotSceneConfig.Process != Game.Options.Process)
+                            if (robotSceneConfig.Process != Options.Instance.Process)
                             {
                                 continue;
                             }
@@ -40,7 +40,7 @@ namespace ET.Server
                             StartSceneConfig robotSceneConfig = thisProcessRobotScenes[index];
                             Scene robotScene = Game.Scene.Get(robotSceneConfig.Id);
                             RobotManagerComponent robotManagerComponent = robotScene.GetComponent<RobotManagerComponent>();
-                            Scene robot = await robotManagerComponent.NewRobot(Game.Options.Process * 10000 + i);
+                            Scene robot = await robotManagerComponent.NewRobot(Options.Instance.Process * 10000 + i);
                             robot.AddComponent<AIComponent, int>(1);
                             Log.Console($"create robot {robot.Zone}");
                             await TimerComponent.Instance.WaitAsync(2000);

+ 4 - 4
Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Watcher/WatcherHelper.cs

@@ -44,11 +44,11 @@ namespace ET.Server
             string arguments = $"App.dll" + 
                     $" --Process={startProcessConfig.Id}" +
                     $" --AppType=Server" +  
-                    $" --StartConfig={Game.Options.StartConfig}" +
-                    $" --Develop={Game.Options.Develop}" +
+                    $" --StartConfig={Options.Instance.StartConfig}" +
+                    $" --Develop={Options.Instance.Develop}" +
                     $" --CreateScenes={createScenes}" +
-                    $" --LogLevel={Game.Options.LogLevel}" +
-                    $" --Console={Game.Options.Console}";
+                    $" --LogLevel={Options.Instance.LogLevel}" +
+                    $" --Console={Options.Instance.Console}";
             Log.Debug($"{exe} {arguments}");
             Process process = ProcessHelper.Run(exe, arguments);
             return process;

+ 2 - 2
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/AOI/AOIEntitySystem.cs

@@ -136,7 +136,7 @@ namespace ET.Server
                     enter.BeSeeUnits.Add(self.Id, self);
                 }
             }
-            Game.EventSystem.Publish(self.DomainScene(), new EventType.UnitEnterSightRange() { A = self, B = enter });
+            EventSystem.Instance.Publish(self.DomainScene(), new EventType.UnitEnterSightRange() { A = self, B = enter });
         }
 
         // leave离开self视野
@@ -164,7 +164,7 @@ namespace ET.Server
                 leave.BeSeePlayers.Remove(self.Id);
             }
 
-            Game.EventSystem.Publish(self.DomainScene(), new EventType.UnitLeaveSightRange { A = self, B = leave });
+            EventSystem.Instance.Publish(self.DomainScene(), new EventType.UnitLeaveSightRange { A = self, B = leave });
         }
 
         /// <summary>

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/Actor/ActorMessageDispatcherComponentSystem.cs

@@ -47,7 +47,7 @@ namespace ET.Server
         {
             self.ActorMessageHandlers.Clear();
 
-            var types = Game.EventSystem.GetTypes(typeof (ActorMessageHandlerAttribute));
+            var types = EventSystem.Instance.GetTypes(typeof (ActorMessageHandlerAttribute));
             foreach (Type type in types)
             {
                 object obj = Activator.CreateInstance(type);

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/ActorLocation/ActorLocationSenderComponentSystem.cs

@@ -38,7 +38,7 @@ namespace ET.Server
         protected override void Destroy(ActorLocationSenderComponent self)
         {
             ActorLocationSenderComponent.Instance = null;
-            TimerComponent.Instance.Remove(ref self.CheckTimer);
+            TimerComponent.Instance?.Remove(ref self.CheckTimer);
         }
     }
 

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/Console/ReloadConfigConsoleHandler.cs

@@ -18,7 +18,7 @@ namespace ET.Server
                     string[] ss = content.Split(" ");
                     string configName = ss[1];
                     string category = $"{configName}Category";
-                    Type type = Game.EventSystem.GetType($"ET.{category}");
+                    Type type = EventSystem.Instance.GetType($"ET.{category}");
                     if (type == null)
                     {
                         Log.Console($"reload config but not find {category}");

+ 3 - 0
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/Http/HttpComponentSystem.cs

@@ -100,6 +100,9 @@ namespace ET.Server
                     HttpListenerContext context = await self.Listener.GetContextAsync();
                     self.Handle(context).Coroutine();
                 }
+                catch (ObjectDisposedException)
+                {
+                }
                 catch (Exception e)
                 {
                     Log.Error(e);

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/MessageInner/NetInnerComponentSystem.cs

@@ -61,7 +61,7 @@ namespace ET.Server
             }
 
             session.LastRecvTime = TimeHelper.ClientNow();
-            Game.EventSystem.Callback(new SessionStreamCallback() {Id = self.SessionStreamDispatcherType, Session = session, MemoryStream = memoryStream});
+            EventSystem.Instance.Callback(new SessionStreamCallback() {Id = self.SessionStreamDispatcherType, Session = session, MemoryStream = memoryStream});
         }
 
         public static void OnError(this NetInnerComponent self, long channelId, int error)

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/RobotCase/RobotCaseDispatcherComponentSystem.cs

@@ -30,7 +30,7 @@ namespace ET.Server
         {
             self.Dictionary.Clear();
 
-            HashSet<Type> types = Game.EventSystem.GetTypes(typeof(RobotCaseAttribute));
+            HashSet<Type> types = EventSystem.Instance.GetTypes(typeof(RobotCaseAttribute));
 
             foreach (Type type in types)
             {

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/AI/AIDispatcherComponentSystem.cs

@@ -38,7 +38,7 @@ namespace ET
         {
             self.AIHandlers.Clear();
             
-            var types = Game.EventSystem.GetTypes(typeof (AIHandlerAttribute));
+            var types = EventSystem.Instance.GetTypes(typeof (AIHandlerAttribute));
             foreach (Type type in types)
             {
                 AAIHandler aaiHandler = Activator.CreateInstance(type) as AAIHandler;

+ 5 - 5
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Config/ConfigComponentSystem.cs

@@ -27,7 +27,7 @@ namespace ET
 		
 		public static void LoadOneConfig(this ConfigComponent self, Type configType)
 		{
-			byte[] oneConfigBytes = Game.EventSystem.Callback<ConfigComponent.GetOneConfigBytes, byte[]>(new ConfigComponent.GetOneConfigBytes() {ConfigName = configType.FullName});
+			byte[] oneConfigBytes = EventSystem.Instance.Callback<ConfigComponent.GetOneConfigBytes, byte[]>(new ConfigComponent.GetOneConfigBytes() {ConfigName = configType.FullName});
 
 			object category = ProtobufHelper.FromBytes(configType, oneConfigBytes, 0, oneConfigBytes.Length);
 
@@ -37,10 +37,10 @@ namespace ET
 		public static void Load(this ConfigComponent self)
 		{
 			self.AllConfig.Clear();
-			HashSet<Type> types = Game.EventSystem.GetTypes(typeof (ConfigAttribute));
+			HashSet<Type> types = EventSystem.Instance.GetTypes(typeof (ConfigAttribute));
 			
 			Dictionary<string, byte[]> configBytes = 
-			Game.EventSystem.Callback<ConfigComponent.GetAllConfigBytes, Dictionary<string, byte[]>>(
+			EventSystem.Instance.Callback<ConfigComponent.GetAllConfigBytes, Dictionary<string, byte[]>>(
 				new ConfigComponent.GetAllConfigBytes());
 
 			foreach (Type type in types)
@@ -52,10 +52,10 @@ namespace ET
 		public static async ETTask LoadAsync(this ConfigComponent self)
 		{
 			self.AllConfig.Clear();
-			HashSet<Type> types = Game.EventSystem.GetTypes(typeof (ConfigAttribute));
+			HashSet<Type> types = EventSystem.Instance.GetTypes(typeof (ConfigAttribute));
 			
 			Dictionary<string, byte[]> configBytes = 
-					Game.EventSystem.Callback<ConfigComponent.GetAllConfigBytes, Dictionary<string, byte[]>>(
+					EventSystem.Instance.Callback<ConfigComponent.GetAllConfigBytes, Dictionary<string, byte[]>>(
 						new ConfigComponent.GetAllConfigBytes());
 
 			using (ListComponent<Task> listTasks = ListComponent<Task>.Create())

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Message/MessageDispatcherComponentSystem.cs

@@ -42,7 +42,7 @@ namespace ET
         {
             self.Handlers.Clear();
 
-            HashSet<Type> types = Game.EventSystem.GetTypes(typeof (MessageHandlerAttribute));
+            HashSet<Type> types = EventSystem.Instance.GetTypes(typeof (MessageHandlerAttribute));
 
             foreach (Type type in types)
             {

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Message/NetKcpComponentSystem.cs

@@ -58,7 +58,7 @@ namespace ET
 
             session.LastRecvTime = TimeHelper.ClientNow();
 
-            Game.EventSystem.Callback(new SessionStreamCallback() {Id = self.SessionStreamDispatcherType, Session = session, MemoryStream = memoryStream});
+            EventSystem.Instance.Callback(new SessionStreamCallback() {Id = self.SessionStreamDispatcherType, Session = session, MemoryStream = memoryStream});
         }
 
         public static void OnError(this NetKcpComponent self, long channelId, int error)

+ 2 - 2
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Move/MoveComponentSystem.cs

@@ -95,7 +95,7 @@ namespace ET
             self.Speed = speed;
             self.tcs = ETTask<bool>.Create(true);
 
-            Game.EventSystem.Publish(self.DomainScene(), new EventType.MoveStart() {Unit = self.GetParent<Unit>()});
+            EventSystem.Instance.Publish(self.DomainScene(), new EventType.MoveStart() {Unit = self.GetParent<Unit>()});
             
             self.StartMove();
             
@@ -117,7 +117,7 @@ namespace ET
 
             if (moveRet)
             {
-                Game.EventSystem.Publish(self.DomainScene(), new EventType.MoveStop() {Unit = self.GetParent<Unit>()});
+                EventSystem.Instance.Publish(self.DomainScene(), new EventType.MoveStop() {Unit = self.GetParent<Unit>()});
             }
             return moveRet;
         }

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Recast/NavmeshComponentSystem.cs

@@ -21,7 +21,7 @@ namespace ET
                 return ptr;
             }
 
-            byte[] buffer = Game.EventSystem.Callback<NavmeshComponent.RecastFileLoader, byte[]>(new NavmeshComponent.RecastFileLoader() {Name = name});
+            byte[] buffer = EventSystem.Instance.Callback<NavmeshComponent.RecastFileLoader, byte[]>(new NavmeshComponent.RecastFileLoader() {Name = name});
             if (buffer.Length == 0)
             {
                 throw new Exception($"no nav data: {name}");

+ 1 - 1
Unity/Assets/Scripts/Codes/HotfixView/Client/Demo/EntryEvent3_InitClient.cs

@@ -17,7 +17,7 @@ namespace ET.Client
             
             Scene clientScene = await SceneFactory.CreateClientScene(1, "Game", Game.Scene);
             
-            await Game.EventSystem.PublishAsync(clientScene, new EventType.AppStartInitFinish());
+            await EventSystem.Instance.PublishAsync(clientScene, new EventType.AppStartInitFinish());
         }
     }
 }

+ 1 - 1
Unity/Assets/Scripts/Codes/HotfixView/Client/Demo/Opera/OperaComponentSystem.cs

@@ -43,7 +43,7 @@ namespace ET.Client
             if (Input.GetKeyDown(KeyCode.R))
             {
                 CodeLoader.Instance.LoadHotfix();
-                Game.EventSystem.Load();
+                EventSystem.Instance.Load();
                 Log.Debug("hot reload success!");
             }
             

+ 1 - 1
Unity/Assets/Scripts/Codes/HotfixView/Client/Module/UI/UIEventComponentSystem.cs

@@ -25,7 +25,7 @@ namespace ET.Client
 				self.UILayers.Add((int)UILayer.Mid, referenceCollector.Get<GameObject>(UILayer.Mid.ToString()).transform);
 				self.UILayers.Add((int)UILayer.High, referenceCollector.Get<GameObject>(UILayer.High.ToString()).transform);
 
-				var uiEvents = Game.EventSystem.GetTypes(typeof (UIEventAttribute));
+				var uiEvents = EventSystem.Instance.GetTypes(typeof (UIEventAttribute));
 				foreach (Type type in uiEvents)
 				{
 					object[] attrs = type.GetCustomAttributes(typeof(UIEventAttribute), false);

+ 1 - 1
Unity/Assets/Scripts/Codes/Model/Server/Module/MessageInner/NetInnerComponent.cs

@@ -14,7 +14,7 @@ namespace ET.Server
         {
             InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
             this.Process = instanceIdStruct.Process;
-            instanceIdStruct.Process = Game.Options.Process;
+            instanceIdStruct.Process = Options.Instance.Process;
             this.ActorId = instanceIdStruct.ToLong();
         }
     }

+ 4 - 4
Unity/Assets/Scripts/Codes/Model/Share/Entry.cs

@@ -19,16 +19,16 @@
     {
         public static void Start()
         {
-            MongoHelper.Register(Game.EventSystem.GetTypes());
+            MongoRegister.Init();
             
             StartAsync().Coroutine();
         }
         
         private static async ETTask StartAsync()
         {
-            await Game.EventSystem.PublishAsync(Game.Scene, new EventType.EntryEvent1());
-            await Game.EventSystem.PublishAsync(Game.Scene, new EventType.EntryEvent2());
-            await Game.EventSystem.PublishAsync(Game.Scene, new EventType.EntryEvent3());
+            await EventSystem.Instance.PublishAsync(Game.Scene, new EventType.EntryEvent1());
+            await EventSystem.Instance.PublishAsync(Game.Scene, new EventType.EntryEvent2());
+            await EventSystem.Instance.PublishAsync(Game.Scene, new EventType.EntryEvent3());
         }
     }
 }

+ 1 - 1
Unity/Assets/Scripts/Codes/Model/Share/Module/CoroutineLock/CoroutineLockComponent.cs

@@ -98,7 +98,7 @@ namespace ET
                 while (self.timerOutTimer.Count > 0)
                 {
                     long CoroutineLockInstanceId = self.timerOutTimer.Dequeue();
-                    CoroutineLock coroutineLock = Game.EventSystem.Get(CoroutineLockInstanceId) as CoroutineLock;
+                    CoroutineLock coroutineLock = EventSystem.Instance.Get(CoroutineLockInstanceId) as CoroutineLock;
 
                     if (coroutineLock == null)
                     {

+ 7 - 3
Unity/Assets/Scripts/Codes/Model/Share/Module/Log/NLogger.cs

@@ -1,13 +1,17 @@
-using NLog;
+using System;
+using NLog;
 
 namespace ET
 {
     public class NLogger: ILog
     {
-        private readonly Logger logger;
+        private readonly NLog.Logger logger;
 
-        public NLogger(string name)
+        public NLogger(string name, int process, string configPath)
         {
+            LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(configPath);
+            LogManager.Configuration.Variables["appIdFormat"] = $"{process:000000}";
+            LogManager.Configuration.Variables["currentDir"] = Environment.CurrentDirectory;
             this.logger = LogManager.GetLogger(name);
         }
 

+ 2 - 2
Unity/Assets/Scripts/Codes/Model/Share/Module/Message/OpcodeHelper.cs

@@ -37,7 +37,7 @@ namespace ET
                 return;
             }
             
-            Game.ILog.Debug("zone: {0} {1}", zone, message);
+            Logger.Instance.Debug("zone: {0} {1}", zone, message);
         }
         
         public static void LogMsg(ushort opcode, long actorId, object message)
@@ -47,7 +47,7 @@ namespace ET
                 return;
             }
             
-            Game.ILog.Debug("actorId: {0} {1}", actorId, message);
+            Logger.Instance.Debug("actorId: {0} {1}", actorId, message);
         }
     }
 }

+ 2 - 2
Unity/Assets/Scripts/Codes/Model/Share/Module/Message/OpcodeTypeComponent.cs

@@ -17,7 +17,7 @@ namespace ET
                 self.typeOpcodes.Clear();
                 self.requestResponse.Clear();
 
-                HashSet<Type> types = Game.EventSystem.GetTypes(typeof (MessageAttribute));
+                HashSet<Type> types = EventSystem.Instance.GetTypes(typeof (MessageAttribute));
                 foreach (Type type in types)
                 {
                     object[] attrs = type.GetCustomAttributes(typeof (MessageAttribute), false);
@@ -58,7 +58,7 @@ namespace ET
                         }
 
                         ResponseTypeAttribute responseTypeAttribute = attrs[0] as ResponseTypeAttribute;
-                        self.requestResponse.Add(type, Game.EventSystem.GetType($"ET.{responseTypeAttribute.Type}"));
+                        self.requestResponse.Add(type, EventSystem.Instance.GetType($"ET.{responseTypeAttribute.Type}"));
                     }
                 }
             }

+ 1 - 1
Unity/Assets/Scripts/Codes/Model/Share/Module/Numeric/NumericComponent.cs

@@ -60,7 +60,7 @@ namespace ET
 
             if (isPublicEvent)
             {
-                Game.EventSystem.Publish(self.DomainScene(),
+                EventSystem.Instance.Publish(self.DomainScene(),
                     new EventType.NumbericChange() { Unit = self.GetParent<Unit>(), New = value, Old = oldValue, NumericType = numericType });
             }
         }

+ 1 - 1
Unity/Assets/Scripts/Codes/Model/Share/Module/Numeric/NumericWatcherComponent.cs

@@ -29,7 +29,7 @@ namespace ET
         {
             self.allWatchers = new Dictionary<int, List<NumericWatcherInfo>>();
 
-            HashSet<Type> types = Game.EventSystem.GetTypes(typeof(NumericWatcherAttribute));
+            HashSet<Type> types = EventSystem.Instance.GetTypes(typeof(NumericWatcherAttribute));
             foreach (Type type in types)
             {
                 object[] attrs = type.GetCustomAttributes(typeof(NumericWatcherAttribute), false);

+ 2 - 2
Unity/Assets/Scripts/Codes/Model/Share/Module/Timer/TimerComponent.cs

@@ -132,7 +132,7 @@ namespace ET
                 case TimerClass.OnceTimer:
                 {
                     int type = timerAction.Type;
-                    Game.EventSystem.Callback(new TimerCallback() {Id = type, Args = timerAction.Object});
+                    EventSystem.Instance.Callback(new TimerCallback() {Id = type, Args = timerAction.Object});
                     break;
                 }
                 case TimerClass.OnceWaitTimer:
@@ -147,7 +147,7 @@ namespace ET
                     int type = timerAction.Type;
                     long tillTime = TimeHelper.ServerNow() + timerAction.Time;
                     self.AddTimer(tillTime, timerAction);
-                    Game.EventSystem.Callback(new TimerCallback() {Id = type, Args = timerAction.Object});
+                    EventSystem.Instance.Callback(new TimerCallback() {Id = type, Args = timerAction.Object});
                     break;
                 }
             }

+ 2 - 2
Unity/Assets/Scripts/Codes/Model/Share/Module/Unit/Unit.cs

@@ -26,7 +26,7 @@ namespace ET
             {
                 Vector3 oldPos = this.position;
                 this.position = value;
-                Game.EventSystem.Publish(this.DomainScene(), new EventType.ChangePosition() { Unit = this, OldPos = oldPos });
+                EventSystem.Instance.Publish(this.DomainScene(), new EventType.ChangePosition() { Unit = this, OldPos = oldPos });
             }
         }
 
@@ -47,7 +47,7 @@ namespace ET
             set
             {
                 this.rotation = value;
-                Game.EventSystem.Publish(this.DomainScene(), new EventType.ChangeRotation() { Unit = this });
+                EventSystem.Instance.Publish(this.DomainScene(), new EventType.ChangeRotation() { Unit = this });
             }
         }
 

+ 1 - 1
Unity/Assets/Scripts/Codes/ModelView/Client/Demo/Config/ConfigLoader.cs

@@ -15,7 +15,7 @@ namespace ET.Client
                 const string configBundleName = "config.unity3d";
                 ResourcesComponent.Instance.LoadBundle(configBundleName);
                 
-                HashSet<Type> configTypes = Game.EventSystem.GetTypes(typeof (ConfigAttribute));
+                HashSet<Type> configTypes = EventSystem.Instance.GetTypes(typeof (ConfigAttribute));
                 foreach (Type configType in configTypes)
                 {
                     TextAsset v = ResourcesComponent.Instance.GetAsset(configBundleName, configType.Name) as TextAsset;

+ 43 - 27
Unity/Assets/Scripts/Core/Entity/Game.cs

@@ -5,53 +5,69 @@ namespace ET
 {
     public static class Game
     {
-        public static ThreadSynchronizationContext ThreadSynchronizationContext => ThreadSynchronizationContext.Instance;
+        private static readonly Dictionary<Type, ISingleton> singletonTypes = new Dictionary<Type, ISingleton>();
+        private static readonly Stack<ISingleton> singletons = new Stack<ISingleton>();
 
-        public static TimeInfo TimeInfo => TimeInfo.Instance;
+        public static T AddSingleton<T>() where T: Singleton<T>, new()
+        {
+            T singleton = new T();
+            Type singletonType = typeof (T);
+            if (singletonTypes.ContainsKey(singletonType))
+            {
+                throw new Exception($"already exist singleton: {singletonType.Name}");
+            }
+
+            singletonTypes.Add(singletonType, singleton);
+            singletons.Push(singleton);
+            
+            singleton.Register();
+            
+            return singleton;
+        }
         
-        public static EventSystem EventSystem => EventSystem.Instance;
+        public static void AddSingleton(ISingleton singleton)
+        {
+            Type singletonType = singleton.GetType();
+            if (singletonTypes.ContainsKey(singletonType))
+            {
+                throw new Exception($"already exist singleton: {singletonType.Name}");
+            }
+
+            singletonTypes.Add(singletonType, singleton);
+            singletons.Push(singleton);
+            
+            singleton.Register();
+        }
 
-        private static Scene scene;
         public static Scene Scene
         {
             get
             {
-                if (scene != null)
-                {
-                    return scene;
-                }
-                scene = EntitySceneFactory.CreateScene(0, SceneType.Process, "Process");
-                return scene;
+                return Root.Instance.Scene;
             }
         }
 
-        public static ObjectPool ObjectPool => ObjectPool.Instance;
-
-        public static IdGenerater IdGenerater => IdGenerater.Instance;
-
-        public static Options Options => Options.Instance;
-
-        public static ILog ILog { get; set; }
-
         public static void Update()
         {
-            ThreadSynchronizationContext.Update();
-            TimeInfo.Update();
-            EventSystem.Update();
+            ThreadSynchronizationContext.Instance.Update();
+            TimeInfo.Instance.Update();
+            EventSystem.Instance.Update();
         }
         
         public static void LateUpdate()
         {
-            EventSystem.LateUpdate();
+            EventSystem.Instance.LateUpdate();
         }
 
         public static void Close()
         {
-            scene?.Dispose();
-            scene = null;
-            MonoPool.Instance.Dispose();
-            EventSystem.Instance.Dispose();
-            IdGenerater.Instance.Dispose();
+            // 顺序反过来清理
+            while (singletons.Count > 0)
+            {
+                ISingleton iSingleton = singletons.Pop();
+                iSingleton.Destroy();
+            }
+            singletonTypes.Clear();
         }
     }
 }

+ 18 - 0
Unity/Assets/Scripts/Core/Entity/Root.cs

@@ -0,0 +1,18 @@
+namespace ET
+{
+    // 管理根部的Scene
+    public class Root: Singleton<Root>
+    {
+        public Scene Scene;
+
+        public Root()
+        {
+            this.Scene = EntitySceneFactory.CreateScene(0, SceneType.Process, "Process");
+        }
+
+        public override void Dispose()
+        {
+            this.Scene.Dispose();
+        }
+    }
+}

+ 1 - 1
Unity/Assets/Scripts/Core/MonoPool.cs.meta → Unity/Assets/Scripts/Core/Entity/Root.cs.meta

@@ -1,5 +1,5 @@
 fileFormatVersion: 2
-guid: 879f984db902b2a45a08c70214df0a31
+guid: 03d33b697b50f884e87c01a144073436
 MonoImporter:
   externalObjects: {}
   serializedVersion: 2

+ 2 - 2
Unity/Assets/Scripts/Core/HashSetComponent.cs

@@ -7,13 +7,13 @@ namespace ET
     {
         public static HashSetComponent<T> Create()
         {
-            return MonoPool.Instance.Fetch(typeof (HashSetComponent<T>)) as HashSetComponent<T>;
+            return ObjectPool.Instance.Fetch(typeof (HashSetComponent<T>)) as HashSetComponent<T>;
         }
 
         public void Dispose()
         {
             this.Clear();
-            MonoPool.Instance.Recycle(this);
+            ObjectPool.Instance.Recycle(this);
         }
     }
 }

+ 2 - 2
Unity/Assets/Scripts/Core/ListComponent.cs

@@ -7,13 +7,13 @@ namespace ET
     {
         public static ListComponent<T> Create()
         {
-            return MonoPool.Instance.Fetch(typeof (ListComponent<T>)) as ListComponent<T>;
+            return ObjectPool.Instance.Fetch(typeof (ListComponent<T>)) as ListComponent<T>;
         }
 
         public void Dispose()
         {
             this.Clear();
-            MonoPool.Instance.Recycle(this);
+            ObjectPool.Instance.Recycle(this);
         }
     }
 }

+ 14 - 87
Unity/Assets/Scripts/Core/Log/Log.cs

@@ -1,151 +1,78 @@
 using System;
-using System.Diagnostics;
 
 namespace ET
 {
     public static class Log
     {
-        private const int TraceLevel = 1;
-        private const int DebugLevel = 2;
-        private const int InfoLevel = 3;
-        private const int WarningLevel = 4;
-
-        private static bool CheckLogLevel(int level)
-        {
-            if (Options.Instance == null)
-            {
-                return true;
-            }
-            return Options.Instance.LogLevel <= level;
-        }
-        
         public static void Trace(string msg)
         {
-            if (!CheckLogLevel(DebugLevel))
-            {
-                return;
-            }
-            StackTrace st = new StackTrace(1, true);
-            Game.ILog.Trace($"{msg}\n{st}");
+            Logger.Instance.Trace(msg);
         }
 
         public static void Debug(string msg)
         {
-            if (!CheckLogLevel(DebugLevel))
-            {
-                return;
-            }
-            Game.ILog.Debug(msg);
+            Logger.Instance.Debug(msg);
         }
 
         public static void Info(string msg)
         {
-            if (!CheckLogLevel(InfoLevel))
-            {
-                return;
-            }
-            Game.ILog.Info(msg);
+            Logger.Instance.Info(msg);
         }
 
         public static void TraceInfo(string msg)
         {
-            if (!CheckLogLevel(InfoLevel))
-            {
-                return;
-            }
-            StackTrace st = new StackTrace(1, true);
-            Game.ILog.Trace($"{msg}\n{st}");
+            Logger.Instance.Trace(msg);
         }
 
         public static void Warning(string msg)
         {
-            if (!CheckLogLevel(WarningLevel))
-            {
-                return;
-            }
-
-            Game.ILog.Warning(msg);
+            Logger.Instance.Warning(msg);
         }
 
         public static void Error(string msg)
         {
-            StackTrace st = new StackTrace(1, true);
-            Game.ILog.Error($"{msg}\n{st}");
+            Logger.Instance.Error(msg);
         }
 
         public static void Error(Exception e)
         {
-            if (e.Data.Contains("StackTrace"))
-            {
-                Game.ILog.Error($"{e.Data["StackTrace"]}\n{e}");
-                return;
-            }
-            string str = e.ToString();
-            Game.ILog.Error(str);
+            Logger.Instance.Error(e);
         }
 
         public static void Trace(string message, params object[] args)
         {
-            if (!CheckLogLevel(TraceLevel))
-            {
-                return;
-            }
-            StackTrace st = new StackTrace(1, true);
-            Game.ILog.Trace($"{string.Format(message, args)}\n{st}");
+            Logger.Instance.Trace(message, args);
         }
 
         public static void Warning(string message, params object[] args)
         {
-            if (!CheckLogLevel(WarningLevel))
-            {
-                return;
-            }
-            Game.ILog.Warning(string.Format(message, args));
+            Logger.Instance.Warning(string.Format(message, args));
         }
 
         public static void Info(string message, params object[] args)
         {
-            if (!CheckLogLevel(InfoLevel))
-            {
-                return;
-            }
-            Game.ILog.Info(string.Format(message, args));
+            Logger.Instance.Info(string.Format(message, args));
         }
 
         public static void Debug(string message, params object[] args)
         {
-            if (!CheckLogLevel(DebugLevel))
-            {
-                return;
-            }
-            Game.ILog.Debug(string.Format(message, args));
+            Logger.Instance.Debug(string.Format(message, args));
 
         }
 
         public static void Error(string message, params object[] args)
         {
-            StackTrace st = new StackTrace(1, true);
-            string s = string.Format(message, args) + '\n' + st;
-            Game.ILog.Error(s);
+            Logger.Instance.Error(message, args);
         }
         
         public static void Console(string message)
         {
-            if (Options.Instance.Console == 1)
-            {
-                System.Console.WriteLine(message);
-            }
-            Game.ILog.Debug(message);
+            Logger.Instance.Console(message);
         }
         
         public static void Console(string message, params object[] args)
         {
-            string s = string.Format(message, args);
-            if (Options.Instance.Console == 1)
-            {
-                System.Console.WriteLine(s);
-            }
-            Game.ILog.Debug(s);
+            Logger.Instance.Console(message, args);
         }
     }
 }

+ 161 - 0
Unity/Assets/Scripts/Core/Log/Logger.cs

@@ -0,0 +1,161 @@
+using System;
+using System.Diagnostics;
+
+namespace ET
+{
+    public class Logger: Singleton<Logger>
+    {
+        private ILog iLog;
+
+        public ILog ILog
+        {
+            set
+            {
+                this.iLog = value;
+            }
+        }
+        
+        private const int TraceLevel = 1;
+        private const int DebugLevel = 2;
+        private const int InfoLevel = 3;
+        private const int WarningLevel = 4;
+
+        private bool CheckLogLevel(int level)
+        {
+            if (Options.Instance == null)
+            {
+                return true;
+            }
+            return Options.Instance.LogLevel <= level;
+        }
+        
+        public void Trace(string msg)
+        {
+            if (!CheckLogLevel(DebugLevel))
+            {
+                return;
+            }
+            StackTrace st = new StackTrace(2, true);
+            Logger.Instance.Trace($"{msg}\n{st}");
+        }
+
+        public void Debug(string msg)
+        {
+            if (!CheckLogLevel(DebugLevel))
+            {
+                return;
+            }
+            this.iLog.Debug(msg);
+        }
+
+        public void Info(string msg)
+        {
+            if (!CheckLogLevel(InfoLevel))
+            {
+                return;
+            }
+            this.iLog.Info(msg);
+        }
+
+        public void TraceInfo(string msg)
+        {
+            if (!CheckLogLevel(InfoLevel))
+            {
+                return;
+            }
+            StackTrace st = new StackTrace(2, true);
+            this.iLog.Trace($"{msg}\n{st}");
+        }
+
+        public void Warning(string msg)
+        {
+            if (!CheckLogLevel(WarningLevel))
+            {
+                return;
+            }
+
+            this.iLog.Warning(msg);
+        }
+
+        public void Error(string msg)
+        {
+            StackTrace st = new StackTrace(2, true);
+            this.iLog.Error($"{msg}\n{st}");
+        }
+
+        public void Error(Exception e)
+        {
+            if (e.Data.Contains("StackTrace"))
+            {
+                this.iLog.Error($"{e.Data["StackTrace"]}\n{e}");
+                return;
+            }
+            string str = e.ToString();
+            this.iLog.Error(str);
+        }
+
+        public void Trace(string message, params object[] args)
+        {
+            if (!CheckLogLevel(TraceLevel))
+            {
+                return;
+            }
+            StackTrace st = new StackTrace(2, true);
+            this.iLog.Trace($"{string.Format(message, args)}\n{st}");
+        }
+
+        public void Warning(string message, params object[] args)
+        {
+            if (!CheckLogLevel(WarningLevel))
+            {
+                return;
+            }
+            this.iLog.Warning(string.Format(message, args));
+        }
+
+        public void Info(string message, params object[] args)
+        {
+            if (!CheckLogLevel(InfoLevel))
+            {
+                return;
+            }
+            this.iLog.Info(string.Format(message, args));
+        }
+
+        public void Debug(string message, params object[] args)
+        {
+            if (!CheckLogLevel(DebugLevel))
+            {
+                return;
+            }
+            this.iLog.Debug(string.Format(message, args));
+
+        }
+
+        public void Error(string message, params object[] args)
+        {
+            StackTrace st = new StackTrace(2, true);
+            string s = string.Format(message, args) + '\n' + st;
+            this.iLog.Error(s);
+        }
+        
+        public void Console(string message)
+        {
+            if (Options.Instance.Console == 1)
+            {
+                System.Console.WriteLine(message);
+            }
+            this.iLog.Debug(message);
+        }
+        
+        public void Console(string message, params object[] args)
+        {
+            string s = string.Format(message, args);
+            if (Options.Instance.Console == 1)
+            {
+                System.Console.WriteLine(s);
+            }
+            this.iLog.Debug(s);
+        }
+    }
+}

+ 1 - 1
Unity/Assets/Scripts/Core/PoolHelper.cs.meta → Unity/Assets/Scripts/Core/Log/Logger.cs.meta

@@ -1,5 +1,5 @@
 fileFormatVersion: 2
-guid: d2e0afb4b34c8fa48af230b65c9d2ca5
+guid: 7d233baf6c97d1c4da67228e2a2e14e8
 MonoImporter:
   externalObjects: {}
   serializedVersion: 2

+ 0 - 31
Unity/Assets/Scripts/Core/MongoHelper.cs

@@ -1,44 +1,13 @@
 using System;
-using System.Collections.Generic;
 using System.IO;
 using MongoDB.Bson;
 using MongoDB.Bson.IO;
 using MongoDB.Bson.Serialization;
-using MongoDB.Bson.Serialization.Conventions;
-using UnityEngine;
 
 namespace ET
 {
     public static class MongoHelper
     {
-        public static void Register(Dictionary<string, Type> types)
-        {
-            // 自动注册IgnoreExtraElements
-
-            ConventionPack conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) };
-
-            ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true);
-
-            BsonSerializer.RegisterSerializer(typeof(Vector3), new StructBsonSerialize<Vector3>());
-            BsonSerializer.RegisterSerializer(typeof(Vector4), new StructBsonSerialize<Vector4>());
-            BsonSerializer.RegisterSerializer(typeof(Quaternion), new StructBsonSerialize<Quaternion>());
-
-            foreach (Type type in types.Values)
-            {
-                if (!type.IsSubclassOf(typeof (Object)))
-                {
-                    continue;
-                }
-
-                if (type.IsGenericType)
-                {
-                    continue;
-                }
-
-                BsonClassMap.LookupClassMap(type);
-            }
-        }
-        
         public static string ToJson(object obj)
         {
             return obj.ToJson();

+ 44 - 0
Unity/Assets/Scripts/Core/MongoRegister.cs

@@ -0,0 +1,44 @@
+using System;
+using System.Collections.Generic;
+using MongoDB.Bson.Serialization;
+using MongoDB.Bson.Serialization.Conventions;
+using UnityEngine;
+
+namespace ET
+{
+    public static class MongoRegister
+    {
+        public static void Init()
+        {
+        }
+        
+        static MongoRegister()
+        {
+            // 自动注册IgnoreExtraElements
+
+            ConventionPack conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) };
+
+            ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true);
+
+            BsonSerializer.RegisterSerializer(typeof(Vector3), new StructBsonSerialize<Vector3>());
+            BsonSerializer.RegisterSerializer(typeof(Vector4), new StructBsonSerialize<Vector4>());
+            BsonSerializer.RegisterSerializer(typeof(Quaternion), new StructBsonSerialize<Quaternion>());
+
+            Dictionary<string, Type> types = EventSystem.Instance.GetTypes();
+            foreach (Type type in types.Values)
+            {
+                if (!type.IsSubclassOf(typeof (Object)))
+                {
+                    continue;
+                }
+
+                if (type.IsGenericType)
+                {
+                    continue;
+                }
+
+                BsonClassMap.LookupClassMap(type);
+            }
+        }
+    }
+}

+ 11 - 0
Unity/Assets/Scripts/Core/MongoRegister.cs.meta

@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a8164d74e3966de48adac057b79d7c4a
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 0 - 48
Unity/Assets/Scripts/Core/MonoPool.cs

@@ -1,48 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace ET
-{
-    public class MonoPool: IDisposable
-    {
-        private readonly Dictionary<Type, Queue<object>> pool = new Dictionary<Type, Queue<object>>();
-        
-        public static MonoPool Instance = new MonoPool();
-        
-        private MonoPool()
-        {
-        }
-
-        public object Fetch(Type type)
-        {
-            Queue<object> queue = null;
-            if (!pool.TryGetValue(type, out queue))
-            {
-                return Activator.CreateInstance(type);
-            }
-
-            if (queue.Count == 0)
-            {
-                return Activator.CreateInstance(type);
-            }
-            return queue.Dequeue();
-        }
-
-        public void Recycle(object obj)
-        {
-            Type type = obj.GetType();
-            Queue<object> queue = null;
-            if (!pool.TryGetValue(type, out queue))
-            {
-                queue = new Queue<object>();
-                pool.Add(type, queue);
-            }
-            queue.Enqueue(obj);
-        }
-
-        public void Dispose()
-        {
-            this.pool.Clear();
-        }
-    }
-}

+ 13 - 13
Unity/Assets/Scripts/Core/Object/Entity.cs

@@ -361,7 +361,7 @@ namespace ET
             {
                 if (this.children == null)
                 {
-                    this.children = MonoPool.Instance.Fetch<Dictionary<long, Entity>>();
+                    this.children = ObjectPool.Instance.Fetch<Dictionary<long, Entity>>();
                 }
                 return this.children;
             }
@@ -384,7 +384,7 @@ namespace ET
 
             if (this.children.Count == 0)
             {
-                MonoPool.Instance.Recycle(this.children);
+                ObjectPool.Instance.Recycle(this.children);
                 this.children = null;
             }
 
@@ -398,7 +398,7 @@ namespace ET
                 return;
             }
 
-            this.childrenDB = this.childrenDB ?? MonoPool.Instance.Fetch<HashSet<Entity>>();
+            this.childrenDB = this.childrenDB ?? ObjectPool.Instance.Fetch<HashSet<Entity>>();
 
             this.childrenDB.Add(entity);
         }
@@ -419,7 +419,7 @@ namespace ET
 
             if (this.childrenDB.Count == 0 && this.IsNew)
             {
-                MonoPool.Instance.Recycle(this.childrenDB);
+                ObjectPool.Instance.Recycle(this.childrenDB);
                 this.childrenDB = null;
             }
         }
@@ -441,7 +441,7 @@ namespace ET
             {
                 if (this.components == null)
                 {
-                    this.components = MonoPool.Instance.Fetch<Dictionary<Type, Entity>>();
+                    this.components = ObjectPool.Instance.Fetch<Dictionary<Type, Entity>>();
                 }
                 return this.components;
             }
@@ -466,7 +466,7 @@ namespace ET
                 }
 
                 this.components.Clear();
-                MonoPool.Instance.Recycle(this.components);
+                ObjectPool.Instance.Recycle(this.components);
                 this.components = null;
 
                 // 创建的才需要回到池中,从db中不需要回收
@@ -475,7 +475,7 @@ namespace ET
                     this.componentsDB.Clear();
                     if (this.IsNew)
                     {
-                        MonoPool.Instance.Recycle(this.componentsDB);
+                        ObjectPool.Instance.Recycle(this.componentsDB);
                         this.componentsDB = null;
                     }
                 }
@@ -490,7 +490,7 @@ namespace ET
                 }
 
                 this.children.Clear();
-                MonoPool.Instance.Recycle(this.children);
+                ObjectPool.Instance.Recycle(this.children);
                 this.children = null;
 
                 if (this.childrenDB != null)
@@ -499,7 +499,7 @@ namespace ET
                     // 创建的才需要回到池中,从db中不需要回收
                     if (this.IsNew)
                     {
-                        MonoPool.Instance.Recycle(this.childrenDB);
+                        ObjectPool.Instance.Recycle(this.childrenDB);
                         this.childrenDB = null;
                     }
                 }
@@ -545,7 +545,7 @@ namespace ET
             
             if (this.componentsDB == null)
             {
-                this.componentsDB = MonoPool.Instance.Fetch<HashSet<Entity>>();
+                this.componentsDB = ObjectPool.Instance.Fetch<HashSet<Entity>>();
             }
 
             this.componentsDB.Add(component);
@@ -566,7 +566,7 @@ namespace ET
             this.componentsDB.Remove(component);
             if (this.componentsDB.Count == 0 && this.IsNew)
             {
-                MonoPool.Instance.Recycle(this.componentsDB);
+                ObjectPool.Instance.Recycle(this.componentsDB);
                 this.componentsDB = null;
             }
         }
@@ -588,7 +588,7 @@ namespace ET
 
             if (this.components.Count == 0)
             {
-                MonoPool.Instance.Recycle(this.components);
+                ObjectPool.Instance.Recycle(this.components);
                 this.components = null;
             }
 
@@ -738,7 +738,7 @@ namespace ET
             Entity component;
             if (isFromPool)
             {
-                component = ObjectPool.Instance.Fetch(type);
+                component = (Entity)ObjectPool.Instance.Fetch(type);
             }
             else
             {

+ 2 - 22
Unity/Assets/Scripts/Core/Object/EventSystem.cs

@@ -7,7 +7,7 @@ namespace ET
 {
     using OneTypeSystems = UnOrderMultiMap<Type, object>;
 
-    public sealed class EventSystem: IDisposable
+    public class EventSystem: Singleton<EventSystem>
     {
         private class TypeSystems
         {
@@ -75,21 +75,6 @@ namespace ET
             }
         }
 
-        private static EventSystem instance;
-
-        public static EventSystem Instance
-        {
-            get
-            {
-                if (instance == null)
-                {
-                    instance = new EventSystem();
-                }
-
-                return instance;
-            }
-        }
-
         private readonly Dictionary<long, Entity> allEntities = new();
 
         private readonly Dictionary<string, Type> allTypes = new();
@@ -112,7 +97,7 @@ namespace ET
             Max = 3,
         }
 
-        private EventSystem()
+        public EventSystem()
         {
             for (int i = 0; i < this.twoQueues.Length; i++)
             {
@@ -840,10 +825,5 @@ namespace ET
 
             return sb.ToString();
         }
-
-        public void Dispose()
-        {
-            instance = null;
-        }
     }
 }

+ 6 - 14
Unity/Assets/Scripts/Core/Object/IdGenerater.cs

@@ -139,10 +139,9 @@ namespace ET
         }
     }
 
-    public class IdGenerater: IDisposable
+    public class IdGenerater: Singleton<IdGenerater>
     {
         public const int Mask18bit = 0x03ffff;
-        public static IdGenerater Instance = new IdGenerater();
 
         public const int MaxZone = 1024;
         
@@ -185,22 +184,15 @@ namespace ET
             }
         }
 
-        public void Dispose()
-        {
-            this.epoch2020 = 0;
-            this.epochThisYear = 0;
-            this.value = 0;
-        }
-
         private uint TimeSince2020()
         {
-            uint a = (uint)((Game.TimeInfo.FrameTime - this.epoch2020) / 1000);
+            uint a = (uint)((TimeInfo.Instance.FrameTime - this.epoch2020) / 1000);
             return a;
         }
         
         private uint TimeSinceThisYear()
         {
-            uint a = (uint)((Game.TimeInfo.FrameTime - this.epochThisYear) / 1000);
+            uint a = (uint)((TimeInfo.Instance.FrameTime - this.epochThisYear) / 1000);
             return a;
         }
         
@@ -226,7 +218,7 @@ namespace ET
                 }
             }
 
-            InstanceIdStruct instanceIdStruct = new InstanceIdStruct(this.lastInstanceIdTime, Game.Options.Process, this.instanceIdValue);
+            InstanceIdStruct instanceIdStruct = new InstanceIdStruct(this.lastInstanceIdTime, Options.Instance.Process, this.instanceIdValue);
             return instanceIdStruct.ToLong();
         }
 
@@ -251,7 +243,7 @@ namespace ET
                 }
             }
             
-            IdStruct idStruct = new IdStruct(this.lastIdTime, Game.Options.Process, value);
+            IdStruct idStruct = new IdStruct(this.lastIdTime, Options.Instance.Process, value);
             return idStruct.ToLong();
         }
         
@@ -280,7 +272,7 @@ namespace ET
                 }
             }
 
-            UnitIdStruct unitIdStruct = new UnitIdStruct(zone, Game.Options.Process, this.lastUnitIdTime, this.unitIdValue);
+            UnitIdStruct unitIdStruct = new UnitIdStruct(zone, Options.Instance.Process, this.lastUnitIdTime, this.unitIdValue);
             return unitIdStruct.ToLong();
         }
     }

+ 11 - 17
Unity/Assets/Scripts/Core/Object/ObjectPool.cs

@@ -3,46 +3,40 @@ using System.Collections.Generic;
 
 namespace ET
 {
-    public class ObjectPool: IDisposable
+    public class ObjectPool: Singleton<ObjectPool>
     {
-        private readonly Dictionary<Type, Queue<Entity>> pool = new Dictionary<Type, Queue<Entity>>();
+        private readonly Dictionary<Type, Queue<object>> pool = new Dictionary<Type, Queue<object>>();
         
-        public static ObjectPool Instance = new ObjectPool();
-        
-        private ObjectPool()
+        public T Fetch<T>() where T: class
         {
+            return this.Fetch(typeof (T)) as T;
         }
 
-        public Entity Fetch(Type type)
+        public object Fetch(Type type)
         {
-            Queue<Entity> queue = null;
+            Queue<object> queue = null;
             if (!pool.TryGetValue(type, out queue))
             {
-                return Activator.CreateInstance(type) as Entity;
+                return Activator.CreateInstance(type);
             }
 
             if (queue.Count == 0)
             {
-                return Activator.CreateInstance(type) as Entity;
+                return Activator.CreateInstance(type);
             }
             return queue.Dequeue();
         }
 
-        public void Recycle(Entity obj)
+        public void Recycle(object obj)
         {
             Type type = obj.GetType();
-            Queue<Entity> queue = null;
+            Queue<object> queue = null;
             if (!pool.TryGetValue(type, out queue))
             {
-                queue = new Queue<Entity>();
+                queue = new Queue<object>();
                 pool.Add(type, queue);
             }
             queue.Enqueue(obj);
         }
-
-        public void Dispose()
-        {
-            this.pool.Clear();
-        }
     }
 }

+ 8 - 10
Unity/Assets/Scripts/Core/Options.cs

@@ -13,30 +13,28 @@ namespace ET
         Proto2CS
     }
     
-    public class Options
+    public class Options: Singleton<Options>
     {
-        public static Options Instance { get; set; }
-        
         [Option("AppType", Required = false, Default = AppType.Server, HelpText = "AppType enum")]
         public AppType AppType { get; set; }
-        
-        [Option("StartConfig", Required = false)]
+
+        [Option("StartConfig", Required = false, Default = "StartConfig/Localhost")]
         public string StartConfig { get; set; }
 
         [Option("Process", Required = false, Default = 1)]
-        public int Process { get; set; } = 1;
+        public int Process { get; set; }
         
         [Option("Develop", Required = false, Default = 0, HelpText = "develop mode, 0正式 1开发 2压测")]
-        public int Develop { get; set; } = 0;
+        public int Develop { get; set; }
 
         [Option("LogLevel", Required = false, Default = 2)]
-        public int LogLevel { get; set; } = 2;
+        public int LogLevel { get; set; }
         
         [Option("Console", Required = false, Default = 0)]
-        public int Console { get; set; } = 0;
+        public int Console { get; set; }
 
         // 进程启动是否创建该进程的scenes
         [Option("CreateScenes", Required = false, Default = 1)]
-        public int CreateScenes { get; set; } = 1;
+        public int CreateScenes { get; set; }
     }
 }

+ 0 - 10
Unity/Assets/Scripts/Core/PoolHelper.cs

@@ -1,10 +0,0 @@
-namespace ET
-{
-    public static class PoolHelper
-    {
-        public static T Fetch<T>(this MonoPool monoPool) where T: class
-        {
-            return monoPool.Fetch(typeof (T)) as T;
-        }
-    }
-}

+ 43 - 0
Unity/Assets/Scripts/Core/Singleton.cs

@@ -0,0 +1,43 @@
+using System;
+
+namespace ET
+{
+    public interface ISingleton
+    {
+        void Register();
+        void Destroy();
+    }
+    
+    public abstract class Singleton<T>: ISingleton, IDisposable where T: Singleton<T>, new()
+    {
+        private static T instance;
+
+        public static T Instance
+        {
+            get
+            {
+                return instance;
+            }
+        }
+
+        public void Register()
+        {
+            if (instance != null)
+            {
+                throw new Exception($"singleton register twice! {typeof (T).Name}");
+            }
+            instance = (T)this;
+        }
+
+        public void Destroy()
+        {
+            T t = instance;
+            instance = null;
+            t.Dispose();
+        }
+
+        public virtual void Dispose()
+        {
+        }
+    }
+}

+ 11 - 0
Unity/Assets/Scripts/Core/Singleton.cs.meta

@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2f8e04e0b283d2f41ab35793b69e9fbb
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 6 - 11
Unity/Assets/Scripts/Core/TimeInfo.cs

@@ -2,10 +2,8 @@ using System;
 
 namespace ET
 {
-    public class TimeInfo: IDisposable
+    public class TimeInfo: Singleton<TimeInfo>
     {
-        public static TimeInfo Instance = new TimeInfo();
-
         private int timeZone;
         
         public int TimeZone
@@ -21,15 +19,17 @@ namespace ET
             }
         }
         
-        private readonly DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
-        private DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+        private DateTime dt1970;
+        private DateTime dt;
         
         public long ServerMinusClientTime { private get; set; }
 
         public long FrameTime;
 
-        private TimeInfo()
+        public TimeInfo()
         {
+            this.dt1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+            this.dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
             this.FrameTime = this.ClientNow();
         }
 
@@ -71,10 +71,5 @@ namespace ET
         {
             return (d.Ticks - dt.Ticks) / 10000;
         }
-
-        public void Dispose()
-        {
-            Instance = null;
-        }
     }
 }

+ 5 - 24
Unity/Assets/Scripts/Mono/CodeLoader.cs

@@ -6,28 +6,9 @@ using UnityEngine;
 
 namespace ET
 {
-	public class CodeLoader: IDisposable
+	public class CodeLoader: Singleton<CodeLoader>
 	{
 		private Assembly assembly;
-		
-		private static CodeLoader instance;
-		
-		public static CodeLoader Instance 
-		{
-			get
-			{
-				return instance ??= new CodeLoader();
-			}
-		}
-
-		private CodeLoader()
-		{
-		}
-		
-		public void Dispose()
-		{
-			instance = null;
-		}
 
 		public void Start()
 		{
@@ -53,7 +34,7 @@ namespace ET
 
 
 					Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof (Game).Assembly, this.assembly);
-					Game.EventSystem.Add(types);
+					EventSystem.Instance.Add(types);
 					
 					break;
 				}
@@ -80,7 +61,7 @@ namespace ET
 
 					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
 					Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(assemblies);
-					Game.EventSystem.Add(types);
+					EventSystem.Instance.Add(types);
 					foreach (Assembly ass in assemblies)
 					{
 						string name = ass.GetName().Name;
@@ -99,7 +80,7 @@ namespace ET
 
 		// 热重载调用下面两个方法
 		// CodeLoader.Instance.LoadLogic();
-		// Game.EventSystem.Load();
+		// EventSystem.Instance.Load();
 		public void LoadHotfix()
 		{
 			if (Init.Instance.GlobalConfig.LoadMode != LoadMode.Reload)
@@ -122,7 +103,7 @@ namespace ET
 			
 			Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof (Game).Assembly, this.assembly, hotfixAssembly);
 			
-			Game.EventSystem.Add(types);
+			EventSystem.Instance.Add(types);
 		}
 	}
 }

+ 17 - 6
Unity/Assets/Scripts/Mono/MonoBehaviour/Init.cs

@@ -1,5 +1,6 @@
 using System;
 using System.Threading;
+using CommandLine;
 using UnityEngine;
 
 namespace ET
@@ -22,14 +23,25 @@ namespace ET
 			};
 				
 			SynchronizationContext.SetSynchronizationContext(ThreadSynchronizationContext.Instance);
+
+			// 命令行参数
+			Options options = null;
+			string[] args = "".Split(" ");
+			Parser.Default.ParseArguments<Options>(args)
+				.WithNotParsed(error => throw new Exception($"命令行格式错误! {error}"))
+				.WithParsed(o => { options = o; });
+			
+			Game.AddSingleton(options);
+			Game.AddSingleton<TimeInfo>();
+			Game.AddSingleton<Logger>().ILog = new UnityLogger();
+			Game.AddSingleton<ObjectPool>();
+			Game.AddSingleton<IdGenerater>();
+			Game.AddSingleton<EventSystem>();
+			Game.AddSingleton<Root>();
 			
-			Game.ILog = new UnityLogger();
-				
 			ETTask.ExceptionHandler += Log.Error;
 
-			Options.Instance = new Options();
-			
-			CodeLoader.Instance.Start();
+			Game.AddSingleton<CodeLoader>().Start();
 		}
 
 		private void Update()
@@ -45,7 +57,6 @@ namespace ET
 		private void OnApplicationQuit()
 		{
 			Game.Close();
-			CodeLoader.Instance.Dispose();
 		}
 	}
 }

+ 3 - 3
Unity/Assets/Scripts/ThirdParty/ETTask/ETTask.cs

@@ -49,12 +49,12 @@ namespace ET
             
             this.state = AwaiterStatus.Pending;
             this.callback = null;
-            queue.Enqueue(this);
-            // 太多了,回收一下
+            // 太多了
             if (queue.Count > 1000)
             {
-                queue.Clear();
+                return;
             }
+            queue.Enqueue(this);
         }
 
         private bool fromPool;

+ 2 - 0
Unity/Packages/manifest.json

@@ -1,6 +1,8 @@
 {
   "dependencies": {
     "com.unity.ide.rider": "3.0.15",
+    "com.unity.ide.visualstudio": "2.0.16",
+    "com.unity.ide.vscode": "1.2.5",
     "com.unity.render-pipelines.universal": "12.1.7",
     "com.unity.textmeshpro": "3.0.6",
     "com.unity.timeline": "1.7.1",

+ 3 - 1
Unity/ProjectSettings/EditorSettings.asset

@@ -11,6 +11,7 @@ EditorSettings:
   m_PrefabUIEnvironment: {fileID: 0}
   m_SpritePackerMode: 5
   m_SpritePackerPaddingPower: 1
+  m_Bc7TextureCompressor: 0
   m_EtcTextureCompressorBehavior: 0
   m_EtcTextureFastCompressor: 2
   m_EtcTextureNormalCompressor: 2
@@ -30,8 +31,8 @@ EditorSettings:
   m_UseLegacyProbeSampleCount: 1
   m_SerializeInlineMappingsOnOneLine: 0
   m_DisableCookiesInLightmapper: 1
-  m_UseCloudEnlightenBake: 0
   m_AssetPipelineMode: 1
+  m_RefreshImportMode: 0
   m_CacheServerMode: 0
   m_CacheServerEndpoint: 
   m_CacheServerNamespacePrefix: default
@@ -39,3 +40,4 @@ EditorSettings:
   m_CacheServerEnableUpload: 1
   m_CacheServerEnableAuth: 0
   m_CacheServerEnableTls: 0
+  m_CacheServerValidationMode: 2