Просмотр исходного кода

增加UI组件,用来创建管理所有UI

tanghai 9 лет назад
Родитель
Сommit
d4d39b7b73

+ 4 - 1
Server/Controller/Message/C2G_LoginGateHandler.cs

@@ -7,7 +7,7 @@ namespace Controller
 	[MessageHandler(AppType.Gate)]
 	public class C2G_LoginGateHandler : AMRpcHandler<C2G_LoginGate, G2C_LoginGate>
 	{
-		protected override void Run(Session session, C2G_LoginGate message, Action<G2C_LoginGate> reply)
+		protected override async void Run(Session session, C2G_LoginGate message, Action<G2C_LoginGate> reply)
 		{
 			bool isCheckOK = Game.Scene.GetComponent<GateSessionKeyComponent>().Check(message.Key);
 			G2C_LoginGate g2CLoginGate = new G2C_LoginGate();
@@ -17,6 +17,9 @@ namespace Controller
 				g2CLoginGate.Message = "Gate key验证失败!";
 			}
 			reply(g2CLoginGate);
+
+			await Game.Scene.GetComponent<TimerComponent>().WaitAsync(5000);
+			session.Dispose();
 		}
 	}
 }

+ 32 - 23
Unity/Assets/Scripts/Component/ChildrenComponent.cs

@@ -1,6 +1,5 @@
 using System.Collections.Generic;
 using System.Linq;
-using Base;
 using MongoDB.Bson.Serialization.Attributes;
 
 namespace Model
@@ -8,12 +7,12 @@ namespace Model
 	/// <summary>
 	/// 父子层级信息
 	/// </summary>
-    public class ChildrenComponent: Component
+    public class ChildrenComponent<T>: Component where T: Entity
     {
 		[BsonIgnore]
-		public Entity Parent { get; private set; }
+		public T Parent { get; private set; }
 		
-		private readonly Dictionary<long, Entity> idChildren = new Dictionary<long, Entity>();
+		private readonly Dictionary<long, T> idChildren = new Dictionary<long, T>();
 
 		[BsonIgnore]
 		public int Count
@@ -24,20 +23,20 @@ namespace Model
 			}
 		}
 
-		public void Add(Entity entity)
+		public void Add(T child)
 		{
-			entity.GetComponent<ChildrenComponent>().Parent = this.Owner;
-			this.idChildren.Add(entity.Id, entity);
+			child.GetComponent<ChildrenComponent<T>>().Parent = (T)this.Owner;
+			this.idChildren.Add(child.Id, child);
 		}
 
-		public Entity Get(long id)
+		public T Get(long id)
 		{
-			Entity entity = null;
-			this.idChildren.TryGetValue(id, out entity);
-			return entity;
+			T child = null;
+			this.idChildren.TryGetValue(id, out child);
+			return child;
 		}
 
-		public Entity[] GetChildren()
+		public T[] GetChildren()
 		{
 			return this.idChildren.Values.ToArray();
 		}
@@ -50,12 +49,12 @@ namespace Model
 
 		public void Remove(long id)
 		{
-			Entity entity;
-			if (!this.idChildren.TryGetValue(id, out entity))
+			T child;
+			if (!this.idChildren.TryGetValue(id, out child))
 			{
 				return;
 			}
-			this.Remove(entity);
+			this.Remove(child);
 		}
 
 		public override void Dispose()
@@ -67,25 +66,35 @@ namespace Model
 
 			base.Dispose();
 
-			foreach (Entity entity in this.idChildren.Values.ToArray())
+			foreach (T child in this.idChildren.Values.ToArray())
 			{
-				entity.Dispose();
+				child.Dispose();
 			}
 
-			this.Parent?.GetComponent<ChildrenComponent>().Remove(this.Id);
+			this.Parent?.GetComponent<ChildrenComponent<T>>().Remove(this.Id);
 		}
     }
 
-	public static partial class ChildrenHelper
+	public static class ChildrenHelper
 	{
-		public static void Add(this Entity entity, Entity child)
+		public static void AddChild<T>(this T parent, T child) where T: Entity
 		{
-			entity.GetComponent<ChildrenComponent>().Add(child);
+			parent.GetComponent<ChildrenComponent<T>>().Add(child);
 		}
 
-		public static void Remove(this Entity entity, long id)
+		public static void RemoveChild<T>(this T entity, long id) where T: Entity
 		{
-			entity.GetComponent<ChildrenComponent>().Remove(id);
+			entity.GetComponent<ChildrenComponent<T>>().Remove(id);
+		}
+
+		public static T GetChild<T>(this T entity, long id) where T: Entity
+		{
+			return entity.GetComponent<ChildrenComponent<T>>().Get(id);
+		}
+
+		public static T[] GetChildren<T>(this T entity) where T: Entity
+		{
+			return entity.GetComponent<ChildrenComponent<T>>().GetChildren();
 		}
 	}
 }

+ 82 - 0
Unity/Assets/Scripts/Component/ResourcesComponent.cs

@@ -0,0 +1,82 @@
+using System;
+using System.Collections.Generic;
+using UnityEngine;
+#if UNITY_EDITOR
+using UnityEditor;
+#endif
+
+namespace Model
+{
+	// 用来实例化资源,暂时直接加载,之后可以预先加载
+	public class ResourcesComponent: Component
+	{
+		public static AssetBundleManifest AssetBundleManifestObject { get; set; }
+
+		private readonly Dictionary<string, UnityEngine.Object> resourceCache = new Dictionary<string, UnityEngine.Object>();
+
+		private readonly Dictionary<string, AssetBundle> bundleCaches = new Dictionary<string, AssetBundle>();
+
+		public K GetUnitRefrenceById<K>(string unitId, EntityType entityType) where K : class
+        {
+            string assetBundleName = $"unit/{AssetBundleHelper.GetBundleNameById(unitId, entityType)}";
+			return GetAsset<K>(assetBundleName, unitId);
+        }
+
+		public K GetReference<K>(string bundle, string prefab, string key) where K : class
+		{
+			GameObject gameObject = this.GetAsset<GameObject>(bundle, prefab);
+			return gameObject.GetComponent<ReferenceCollector>().Get<K>(key);
+		}
+
+		public K GetAsset<K>(string bundleName, string prefab) where K : class
+		{
+			string path = $"{bundleName}.unity3d/{prefab}".ToLower();
+
+			UnityEngine.Object resource = null;
+			if (this.resourceCache.TryGetValue(path, out resource))
+			{
+				return resource as K;
+			}
+
+			if (Define.LoadResourceType == LoadResourceType.Async)
+			{
+				if (!this.bundleCaches.ContainsKey($"{bundleName}.unity3d".ToLower()))
+				{
+					return null;
+				}
+
+				throw new ConfigException($"异步加载资源,资源不在resourceCache中: {bundleName} {path}");
+			}
+
+			try
+			{
+#if UNITY_EDITOR
+				string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(bundleName.ToLower() + ".unity3d", prefab);
+				resource = AssetDatabase.LoadAssetAtPath(realPath[0], typeof (GameObject));
+				this.resourceCache.Add(path, resource);
+#endif
+			}
+			catch (Exception e)
+			{
+				throw new ConfigException($"加载资源出错,输入路径:{path}", e);
+			}
+
+			return resource as K;
+		}
+
+	    public override void Dispose()
+	    {
+		    if (this.Id == 0)
+		    {
+			    return;
+		    }
+
+	        base.Dispose();
+
+	        foreach (var assetBundle in bundleCaches)
+	        {
+                assetBundle.Value?.Unload(true);
+			}
+        }
+	}
+}

+ 12 - 0
Unity/Assets/Scripts/Component/ResourcesComponent.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 509cf7df1ed2a52438a824cb162c208a
+timeCreated: 1478516097
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 149 - 0
Unity/Assets/Scripts/Component/UIComponent.cs

@@ -0,0 +1,149 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using UnityEngine;
+
+namespace Model
+{
+	[ObjectEvent]
+	public class UIComponentEvent : ObjectEvent<UIComponent>, IAwake, ILoader
+	{
+		public void Load()
+		{
+			UIComponent component = GetValue();
+			component.Load();
+		}
+
+		public void Awake()
+		{
+			this.GetValue().Awake();
+		}
+	}
+	
+	/// <summary>
+	/// 管理所有UI
+	/// </summary>
+	public class UIComponent: Component
+	{
+        private UI Root;
+		private Dictionary<UIType, IUIFactory> UiTypes;
+		private readonly Dictionary<UIType, UI> uis = new Dictionary<UIType, UI>();
+
+		public override void Dispose()
+		{
+			if (this.Id == 0)
+			{
+				return;
+			}
+
+			base.Dispose();
+
+			foreach (UIType type in uis.Keys.ToArray())
+			{
+				UI ui;
+				if (!uis.TryGetValue(type, out ui))
+				{
+					continue;
+				}
+				uis.Remove(type);
+				ui.Dispose();
+			}
+		}
+
+		public void Awake()
+		{
+			GameObject uiCanvas = GameObject.Find("/UICanvas");
+			uiCanvas.GetComponent<Canvas>().worldCamera = GameObject.Find("/Camera").GetComponent<Camera>();
+			this.Root = new UI(this.GetOwner<Scene>(), UIType.Root, null, uiCanvas);
+			this.Load();
+		}
+
+		public void Load()
+		{
+			this.UiTypes = new Dictionary<UIType, IUIFactory>();
+
+			Assembly[] assemblies = ObjectManager.Instance.GetAssemblies();
+			foreach (Assembly assembly in assemblies)
+			{
+				Type[] types = assembly.GetTypes();
+				foreach (Type type in types)
+				{
+					object[] attrs = type.GetCustomAttributes(typeof(UIFactoryAttribute), false);
+					if (attrs.Length == 0)
+					{
+						continue;
+					}
+
+					UIFactoryAttribute attribute = attrs[0] as UIFactoryAttribute;
+					if (this.UiTypes.ContainsKey(attribute.Type))
+					{
+						throw new GameException($"已经存在同类UI Factory: {attribute.Type}");
+					}
+					IUIFactory iIuiFactory = Activator.CreateInstance(type) as IUIFactory;
+					if (iIuiFactory == null)
+					{
+						throw new GameException("UI Factory没有继承IUIFactory");
+					}
+					this.UiTypes.Add(attribute.Type, iIuiFactory);
+				}
+			}
+		}
+
+		public UI Create(UIType type)
+		{
+			try
+			{
+				UI ui = this.UiTypes[type].Create(this.GetOwner<Scene>(), type, this.Root);
+				this.uis.Add(type, ui);
+				return ui;
+			}
+			catch (Exception e)
+			{
+				throw new Exception($"{type} UI 错误: {e}");
+			}
+		}
+
+		public void Add(UIType type, UI ui)
+		{
+			this.uis.Add(type, ui);
+		}
+
+		public void Remove(UIType type)
+		{
+			UI ui;
+			if (!this.uis.TryGetValue(type, out ui))
+			{
+				return;
+			}
+			this.uis.Remove(type);
+			ui.Dispose();
+		}
+
+		public void RemoveAll()
+		{
+			foreach (UIType type in this.uis.Keys.ToArray())
+			{
+				UI ui;
+				if (!this.uis.TryGetValue(type, out ui))
+				{
+					continue;
+				}
+				this.uis.Remove(type);
+				ui.Dispose();
+			}
+		}
+		
+		public UI Get(UIType type)
+		{
+			UI ui;
+			this.uis.TryGetValue(type, out ui);
+			return ui;
+		}
+
+		public List<UIType> GetUITypeList()
+		{
+			return new List<UIType>(this.uis.Keys);
+		}
+	}
+}

+ 12 - 0
Unity/Assets/Scripts/Component/UIComponent.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 44e829de290b6374c879adcf05b10151
+timeCreated: 1478510684
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 19 - 6
Unity/Assets/Scripts/Entity/UI.cs

@@ -4,13 +4,19 @@ namespace Model
 {
 	public sealed class UI: Entity
 	{
-		public Entity Scene { get; set; }
+		public Scene Scene { get; set; }
 
-		public UIType UIType { get; set; }
+		public UIType UIType { get; }
 
-		public string Name { get; set; }
+		public string Name
+		{
+			get
+			{
+				return this.GameObject.name;
+			}
+		}
 
-		public GameObject GameObject { get; set; }
+		public GameObject GameObject { get; }
 		
 		public override void Dispose()
 		{
@@ -22,12 +28,19 @@ namespace Model
 			base.Dispose();
 		}
 
-		public UI(): base(EntityType.UI)
+		public void SetAsFirstSibling()
 		{
+			this.GameObject.transform.SetAsFirstSibling();
 		}
 
-		public UI(long id): base(id, EntityType.UI)
+		public UI(Scene scene, UIType uiType, UI parent, GameObject gameObject) : base(EntityType.UI)
 		{
+			this.Scene = scene;
+			this.UIType = uiType;
+
+			gameObject.transform.SetParent(parent?.GameObject.transform);
+			this.GameObject = gameObject;
+			this.AddComponent<ChildrenComponent<UI>>();
 		}
 	}
 }

+ 27 - 0
Unity/Assets/Scripts/Helper/AssetBundleHelper.cs

@@ -0,0 +1,27 @@
+using Model;
+
+namespace Model
+{
+    public static class AssetBundleHelper
+    {
+		public static string GetBundleNameById(string id, EntityType entityType = EntityType.None)
+		{
+			string subString = id.Substring(0, 3);
+			switch (subString[0])
+			{
+				case '1':
+				case '2':
+				case '3':
+					return "3000";
+				case '4':
+				case '5':
+				case '6':
+				case '8':
+					return subString;
+				case '9':
+					return "900";
+			}
+			return subString;
+		}
+	}
+}

+ 12 - 0
Unity/Assets/Scripts/Helper/AssetBundleHelper.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 4076d2797f1e0454fbfb5e79aec99e77
+timeCreated: 1478516097
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 31 - 0
Unity/Assets/Scripts/Other/Define.cs

@@ -0,0 +1,31 @@
+namespace Model
+{
+	public enum LoadResourceType
+	{
+		Async,
+		Sync
+	}
+
+	public static class Define
+	{
+		public const int FlyStartV = 7;
+		public const int GravityAcceleration = 36;
+#if UNITY_EDITOR && !ASYNC
+		public static LoadResourceType LoadResourceType = LoadResourceType.Sync;
+#else
+        public static LoadResourceType LoadResourceType = LoadResourceType.Async;
+#endif
+
+#if UNITY_EDITOR
+		public static bool IsEditorMode = true;
+#else
+		public static bool IsEditorMode = false;
+#endif
+
+#if DEVELOPMENT_BUILD
+		public static bool IsDevelopmentBuild = true;
+#else
+		public static bool IsDevelopmentBuild = false;
+#endif
+	}
+}

+ 12 - 0
Unity/Assets/Scripts/Other/Define.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 951ed8c88c565c74cabe30a086b0863e
+timeCreated: 1478516097
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 7 - 0
Unity/Assets/Scripts/Other/IUIFactory.cs

@@ -0,0 +1,7 @@
+namespace Model
+{
+	public interface IUIFactory
+	{
+		UI Create(Scene scene, UIType type, UI parent);
+	}
+}

+ 12 - 0
Unity/Assets/Scripts/Other/IUIFactory.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 44cebd75ae43115438d62f2cdf56cc63
+timeCreated: 1478510684
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 42 - 0
Unity/Assets/Scripts/Other/LayerNames.cs

@@ -0,0 +1,42 @@
+using UnityEngine;
+
+namespace Model
+{
+	public static class LayerNames
+	{
+		/// <summary>
+		/// UI层
+		/// </summary>
+		public const string UI = "UI";
+
+		/// <summary>
+		/// 游戏单位层
+		/// </summary>
+		public const string UNIT = "Unit";
+
+		/// <summary>
+		/// 地形层
+		/// </summary>
+		public const string MAP = "Map";
+
+		/// <summary>
+		/// 默认层
+		/// </summary>
+		public const string DEFAULT = "Default";
+
+		/// <summary>
+		/// 通过Layers名字得到对应层
+		/// </summary>
+		/// <param name="name"></param>
+		/// <returns></returns>
+		public static int GetLayerInt(string name)
+		{
+			return LayerMask.NameToLayer(name);
+		}
+
+		public static string GetLayerStr(int name)
+		{
+			return LayerMask.LayerToName(name);
+		}
+	}
+}

+ 12 - 0
Unity/Assets/Scripts/Other/LayerNames.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: 8ef788fbad31e454bb0cb2b5c5c246c5
+timeCreated: 1478511150
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 0 - 1
Unity/Assets/Scripts/Other/Options.cs

@@ -1,6 +1,5 @@
 using System;
 using Base;
-using MongoDB.Bson.Serialization.Attributes;
 #if SERVER
 using CommandLine;
 #endif

+ 15 - 0
Unity/Assets/Scripts/Other/UIFactoryAttribute.cs

@@ -0,0 +1,15 @@
+using System;
+
+namespace Model
+{
+	[AttributeUsage(AttributeTargets.Class)]
+	public class UIFactoryAttribute: Attribute
+	{
+		public UIType Type { get; private set; }
+
+		public UIFactoryAttribute(UIType type)
+		{
+			this.Type = type;
+		}
+	}
+}

+ 12 - 0
Unity/Assets/Scripts/Other/UIFactoryAttribute.cs.meta

@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: ea801aa284d9faa46bd1fb6751f50c4d
+timeCreated: 1478510684
+licenseType: Pro
+MonoImporter:
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 1 - 1
Unity/Assets/Scripts/Other/UIType.cs

@@ -2,7 +2,7 @@
 {
 	public enum UIType
 	{
-		None,
+		Root,
 		UIButton,
 		UILoading,
 		UISkillAndBuff,

+ 22 - 0
Unity/Controller/UI/UILogin/Factory/UILoginFactory.cs

@@ -0,0 +1,22 @@
+using Model;
+using UnityEngine;
+using Object = UnityEngine.Object;
+
+namespace Controller
+{
+    [UIFactory(UIType.UILogin)]
+    public class UILoginFactory : IUIFactory
+    {
+        public UI Create(Scene scene, UIType type, UI parent)
+        {
+            GameObject mainPrefab = Resources.Load<GameObject>("UI/LoginPanel");
+            mainPrefab = Object.Instantiate(mainPrefab);
+			mainPrefab.layer = LayerMask.NameToLayer(LayerNames.UI);
+
+			UI ui = new UI(scene, type, parent, mainPrefab);
+			parent.AddChild(ui);
+            
+            return ui;
+        }
+    }
+}

+ 1 - 0
Unity/Controller/Unity.Controller.csproj

@@ -56,6 +56,7 @@
     <Compile Include="Event\InitSceneStartEvent_InitGame.cs" />
     <Compile Include="Message\R2C_ServerLogHandler.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="UI\UILogin\Factory\UILoginFactory.cs" />
   </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="..\Unity.CSharp.csproj">

+ 7 - 0
Unity/Unity.CSharp.csproj

@@ -93,9 +93,11 @@
     <Compile Include="Assets\Scripts\Component\NetInnerComponent.cs" />
     <Compile Include="Assets\Scripts\Component\NetOuterComponent.cs" />
     <Compile Include="Assets\Scripts\Component\NetworkComponent.cs" />
+    <Compile Include="Assets\Scripts\Component\ResourcesComponent.cs" />
     <Compile Include="Assets\Scripts\Component\RobotComponent.cs" />
     <Compile Include="Assets\Scripts\Component\TimeComponent.cs" />
     <Compile Include="Assets\Scripts\Component\TimerComponent.cs" />
+    <Compile Include="Assets\Scripts\Component\UIComponent.cs" />
     <Compile Include="Assets\Scripts\Config\ACategory.cs" />
     <Compile Include="Assets\Scripts\Config\AConfigComponent.cs" />
     <Compile Include="Assets\Scripts\Config\AConfig.cs" />
@@ -113,6 +115,7 @@
     <Compile Include="Assets\Scripts\Event\EventIdType.cs" />
     <Compile Include="Assets\Scripts\Event\IEvent.cs" />
     <Compile Include="Assets\Scripts\GameObjectHelper.cs" />
+    <Compile Include="Assets\Scripts\Helper\AssetBundleHelper.cs" />
     <Compile Include="Assets\Scripts\Helper\DllHelper.cs" />
     <Compile Include="Assets\Scripts\Init.cs" />
     <Compile Include="Assets\Scripts\Message\AMHandler.cs" />
@@ -136,8 +139,12 @@
     <Compile Include="Assets\Scripts\Object\ObjectManager.cs" />
     <Compile Include="Assets\Scripts\Object\EntityType.cs" />
     <Compile Include="Assets\Scripts\Other\GameException.cs" />
+    <Compile Include="Assets\Scripts\Other\LayerNames.cs" />
+    <Compile Include="Assets\Scripts\Other\Define.cs" />
     <Compile Include="Assets\Scripts\Other\Options.cs" />
     <Compile Include="Assets\Scripts\Entity\Config\StartConfig.cs" />
+    <Compile Include="Assets\Scripts\Other\IUIFactory.cs" />
+    <Compile Include="Assets\Scripts\Other\UIFactoryAttribute.cs" />
     <Compile Include="Assets\Scripts\Other\UIType.cs" />
     <Compile Include="Assets\Scripts\ReferenceCollector.cs" />
   </ItemGroup>