unity 代码导入导出Tag And Layer

| 发布     | 分类 Unity  | 标签 Unity 

数据代码

GameLayer 存储LayersSettingPanel一致的常量,方便其他代码调用
GameTag 存储TagsSettingPanel一致的常量,方便其他代码调用
GameSortingLayer 存储SortingLayerSettingPanel一致的枚举,方便其他代码调用

编辑器代码

GameLayer_Editor 导入,导出Layer Setting
GameTag_Editor 导入,导出Tag Setting
GameSortingLayer_Editor 导入,导出SortingLayer Setting
namespace Games
{
	public partial class GameLayer
	{
		#region Unity Default Lock
		public const int Default			=	1 << 0;
		public const int TransparentFX			=	1 << 1;
		public const int Ignore_Raycast			=	1 << 2;
		public const int Layer3			=	1 << 3;
		public const int Water			=	1 << 4;
		public const int UI			=	1 << 5;
		public const int Layer6			=	1 << 6;
		public const int Layer7			=	1 << 7;
		#endregion


		public const int War_Terrain			=	1 << 8;
		public const int War_Unit			=	1 << 9;
		public const int War_Obstacle			=	1 << 10;
		public const int Layer11			=	1 << 11;
		public const int Layer12			=	1 << 12;
		public const int Layer13			=	1 << 13;
		public const int Layer14			=	1 << 14;
		public const int Layer15			=	1 << 15;
		public const int Layer16			=	1 << 16;
		public const int Layer17			=	1 << 17;
		public const int Layer18			=	1 << 18;
		public const int Layer19			=	1 << 19;
		public const int Layer20			=	1 << 20;
		public const int Layer21			=	1 << 21;
		public const int Layer22			=	1 << 22;
		public const int Layer23			=	1 << 23;
		public const int Layer24			=	1 << 24;
		public const int Layer25			=	1 << 25;
		public const int Layer26			=	1 << 26;
		public const int Layer27			=	1 << 27;
		public const int Layer28			=	1 << 28;
		public const int Layer29			=	1 << 29;
		public const int Layer30			=	1 << 30;
		public const int Layer31			=	1 << 31;


		public static int           customBeginIndex = 8;
		public static string[]      customLayers = {"War_Terrain","War_Unit","War_Obstacle","Layer11","Layer12","Layer13","Layer14","Layer15","Layer16","Layer17","Layer18","Layer19","Layer20","Layer21","Layer22","Layer23","Layer24","Layer25","Layer26","Layer27","Layer28","Layer29","Layer30","Layer31"};
	}
}

#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;


namespace Games
{
	public partial class GameLayer
    {


        [MenuItem("Edit/Game/SetEditorLayer")]
        public static void SetEditorTag ()
        {
            SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
            SerializedProperty it = tagManager.GetIterator();
            while (it.NextVisible(true))
            {
                if(it.name == "layers")
                {
                    int end = Mathf.Min(customBeginIndex + customLayers.Length, it.arraySize);
                    for (int i = customBeginIndex; i < end; i++) 
                    {
                        SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
                        dataPoint.stringValue = customLayers[i - customBeginIndex];
                    }

                    tagManager.ApplyModifiedProperties();
                    if (customBeginIndex + customLayers.Length > 32)
                    {
						Debug.LogFormat("<color=red>Layer不能超过31</color>");
                    }
                    break;
                }
            }
        }

		[MenuItem("Edit/Game/Generate GameLayer.cs")]
		public static void GenerateGameLayer ()
		{
			SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
			SerializedProperty it = tagManager.GetIterator();
			while (it.NextVisible(true))
			{
				if(it.name == "layers")
				{
					StringWriter sw = new StringWriter();
					sw.WriteLine("namespace Games");
					sw.WriteLine("{");
					sw.WriteLine("\tpublic partial class GameLayer");
					sw.WriteLine("\t{");

					sw.WriteLine("\t\t#region Unity Default Lock");
					for (int i = 0; i < 8; i++) 
					{
						SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
						string fieldname = string.IsNullOrEmpty(dataPoint.stringValue) ? "Layer" + i : dataPoint.stringValue.Replace(" ", "_");
						sw.WriteLine(string.Format("\t\tpublic const int {0}\t\t\t=\t1 << {1};", fieldname , i ));

					}
					sw.WriteLine("\t\t#endregion");
					sw.WriteLine("\n");

					List<string> fieldnames = new List<string>();
					for (int i = 8; i < it.arraySize; i++) 
					{
						SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
						string fieldname = string.IsNullOrEmpty(dataPoint.stringValue) ? "Layer" + i : dataPoint.stringValue.Replace(" ", "_");
						sw.WriteLine(string.Format("\t\tpublic const int {0}\t\t\t=\t1 << {1};", fieldname , i ));
						fieldnames.Add(string.Format("\"{0}\"", fieldname));
					}

					string fieldnameStr = "";
					string gap = "";
					for(int i = 0; i < fieldnames.Count; i ++)
					{
						fieldnameStr += gap;
						fieldnameStr += fieldnames[i];
						gap = ",";
					}


					sw.WriteLine("\n");
					sw.WriteLine("\t\tpublic static int           customBeginIndex = 8;");
					sw.WriteLine("\t\tpublic static string[]      customLayers = {"+fieldnameStr+"};");

					sw.WriteLine("\t}");
					sw.WriteLine("}");
					File.WriteAllText(Application.dataPath + "/Game/Scripts/Unity/GameLayer.cs", sw.ToString(), System.Text.Encoding.UTF8);
					AssetDatabase.Refresh();
					break;
				}
			}
		}
    }
}

#endif



namespace Games
{
	public partial class GameTag
	{
		#region Unity Default Lock
		public const string Untagged        = "Untagged";
		public const string Respawn         = "Respawn";
		public const string Finish          = "Finish";
		public const string EditorOnly      = "EditorOnly";
		public const string MainCamera      = "MainCamera";
		public const string Player          = "Player";
		public const string GameController  = "GameController";
		#endregion


		public const string UICamera  = "UICamera";
		public const string War_Terrain  = "War_Terrain";
		public const string War_Unit  = "War_Unit";


		public static int           customBeginIndex = 0;
		public static string[]      customTags = {"UICamera","War_Terrain","War_Unit"};
	}
}


#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;

namespace Games
{
	public partial class GameTag 
    {


        [MenuItem("Edit/Game/SetEditorTag")]
        public static void SetEditorTag ()
        {
            SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
            SerializedProperty it = tagManager.GetIterator();
            while (it.NextVisible(true))
            {
                if(it.name == "tags")
                {

					it.ClearArray();
					int end = customBeginIndex + customTags.Length;
					if(it.arraySize < end)
					{
						it.arraySize = end;
					}

                    for (int i = customBeginIndex; i < end; i++) 
                    {
                        SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
                        dataPoint.stringValue = customTags[i - customBeginIndex];
                    }

                    tagManager.ApplyModifiedProperties();
                    
                    break;
                }
            }
        }

		[MenuItem("Edit/Game/Generate GameTag.cs")]
		public static void GenerateGameTag ()
		{
			SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
			SerializedProperty it = tagManager.GetIterator();
			while (it.NextVisible(true))
			{
				if(it.name == "tags")
				{
					StringWriter sw = new StringWriter();
					sw.WriteLine("namespace Games");
					sw.WriteLine("{");
					sw.WriteLine("\tpublic partial class GameTag");
					sw.WriteLine("\t{");

					sw.WriteLine("\t\t#region Unity Default Lock");
					sw.WriteLine("\t\tpublic const string Untagged        = \"Untagged\";");
					sw.WriteLine("\t\tpublic const string Respawn         = \"Respawn\";");
					sw.WriteLine("\t\tpublic const string Finish          = \"Finish\";");
					sw.WriteLine("\t\tpublic const string EditorOnly      = \"EditorOnly\";");
					sw.WriteLine("\t\tpublic const string MainCamera      = \"MainCamera\";");
					sw.WriteLine("\t\tpublic const string Player          = \"Player\";");
					sw.WriteLine("\t\tpublic const string GameController  = \"GameController\";");

					sw.WriteLine("\t\t#endregion");
					sw.WriteLine("\n");


					string fieldnameStr = "";
					string gap = "";

					for (int i = 0; i < it.arraySize; i++) 
					{
						SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
						string fieldname = string.IsNullOrEmpty(dataPoint.stringValue) ? "Tag" + i : dataPoint.stringValue.Replace(" ", "_");

						sw.WriteLine(string.Format("\t\tpublic const string {0}  = \"{1}\";", fieldname, dataPoint.stringValue));


						fieldnameStr += gap;
						fieldnameStr += string.Format("\"{0}\"", dataPoint.stringValue);
						gap = ",";
					}


					sw.WriteLine("\n");
					sw.WriteLine("\t\tpublic static int           customBeginIndex = 0;");
					sw.WriteLine("\t\tpublic static string[]      customTags = {"+fieldnameStr+"};");

					sw.WriteLine("\t}");
					sw.WriteLine("}");
					File.WriteAllText(Application.dataPath + "/Game/Scripts/Unity/GameTag.cs", sw.ToString(), System.Text.Encoding.UTF8);
					AssetDatabase.Refresh();

					break;
				}
			}
		}
    }
}

#endif



namespace Games
{
	public enum GameSortingLayer
	{
		War_Terrain			=	-2,
		War_Shadow			=	-1,
		Default				=	0,
		War_Unit			=	1,
	}
}


#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using System;
using UnityEditor;
using System.IO;

namespace Games
{
	public class GameSortingLayerEditor
	{
		public static bool IsUseBitIndex = true;

		[MenuItem("Edit/Game/SetEditorSortingLayer")]
		public static void SetEditorTag ()
		{
			SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
			SerializedProperty it = tagManager.GetIterator();
			while (it.NextVisible(true))
			{
				if(it.name == "m_SortingLayers")
				{
					int[] 		ids 	;
					string[] 	names 	;

					EnumUtil.GetValuesAndFieldNames<GameSortingLayer>(out ids, out names);
					it.ClearArray();

					int length = ids.Length;
					if(it.arraySize < length)
					{
						it.arraySize = length;
					}


					for (int i = 0; i < length; i++) 
					{
						SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
						SerializedProperty namePoint = dataPoint.FindPropertyRelative("name");
						SerializedProperty uniqueIDPoint = dataPoint.FindPropertyRelative("uniqueID");
						namePoint.stringValue = names[i];
						uniqueIDPoint.intValue = IsUseBitIndex ? 1 << (ids[i] - 1) : ids[i];
					}

					tagManager.ApplyModifiedProperties();
					break;
				}
			}
		}

		[MenuItem("Edit/Game/Generate GameSortingLayer.cs")]
		public static void GameSortingLayer ()
		{
			SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
			SerializedProperty it = tagManager.GetIterator();
			while (it.NextVisible(true))
			{
				if(it.name == "m_SortingLayers")
				{
					StringWriter sw = new StringWriter();
					sw.WriteLine("namespace Games");
					sw.WriteLine("{");
					sw.WriteLine("\tpublic enum GameSortingLayer");
					sw.WriteLine("\t{");

					int bitIndex = 0;
					for (int i = 0; i < it.arraySize; i++) 
					{
						SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
						SerializedProperty namePoint = dataPoint.FindPropertyRelative("name");
						SerializedProperty uniqueIDPoint = dataPoint.FindPropertyRelative("uniqueID");
						Debug.Log(namePoint.stringValue + " = " + uniqueIDPoint.intValue);
						if(uniqueIDPoint.intValue == 0)
						{
							bitIndex = i;
							break;
						}
					}

					Debug.Log(bitIndex);

					for (int i = 0; i < it.arraySize; i++) 
					{
						SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
						SerializedProperty namePoint = dataPoint.FindPropertyRelative("name");
						SerializedProperty uniqueIDPoint = dataPoint.FindPropertyRelative("uniqueID");
						sw.WriteLine(string.Format("\t\t{0}\t\t\t=\t{1},", namePoint.stringValue.Replace(" ", "_"), IsUseBitIndex ? i - bitIndex : uniqueIDPoint.intValue ));
					}

					sw.WriteLine("\t}");
					sw.WriteLine("}");


					File.WriteAllText(Application.dataPath + "/Game/Scripts/Unity/GameSortingLayer.cs", sw.ToString(), System.Text.Encoding.UTF8);
					AssetDatabase.Refresh();
					break;
				}
			}
		}
	}

}

#endif
using UnityEngine;
using System.Collections;
using System.Reflection;
using System;
using System.Collections.Generic;

public class EnumUtil
{
	public static void GetValuesAndFieldNames<T>(out int[] ids, out string[] names)
	{
		Type type = typeof(T);
		T[] valueArr =(T[]) Enum.GetValues(type);
		List<T> valueList = new List<T>(valueArr);
		valueList.Sort();

		names = new string[valueList.Count];
		ids = new int[valueList.Count];

		for(int i = 0; i < valueList.Count; i ++)
		{

			ids[i] = Convert.ToInt32(valueList[i]);
			names[i] = Enum.GetName(type, valueList[i]);
		}

	}
}

上一篇: 【转】Unity3D中Layers和LayerMask解析
下一篇: unity 查看SerializedProperty信息