unity 设置 layer 代码是自己在一个项目里自定义了自己的tag和layer,但是将自己的项目打包以后,导入一个新建的项目时,自定义的tag于Layer丢失。
在这里为大家实现在导入unitypackage的时候,将自定义的tag或者layer写进用户的项目里。

直接在这里为大家贴代码:

  1. using System;
  2. using System.Collections;
  3. using System.Reflection;
  4. using UnityEditor;
  5. using UnityEngine;
  6.  
  7. public class NewBehaviourScript :AssetPostprocessor
  8. {
  9.  
  10. static void OnPostprocessAllAssets (string[] importedAssets, string[] deletedAssets,string[] movedAssets, string[] movedFromAssetPaths)
  11. {
  12. foreach(string s in importedAssets)
  13. {
  14. if (s.Equals("Assets/NewBehaviourScript.cs"))
  15. {
  16. //增加一个叫momo的tag
  17. AddTag("momo");
  18. //增加一个叫ruoruo的layer
  19. AddLayer("ruoruo");
  20. return ;
  21. }
  22. }  
  23. }
  24.  
  25. static void AddTag(string tag)
  26. {
  27. if(!isHasTag(tag))
  28. {
  29. SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
  30. SerializedProperty it = tagManager.GetIterator();
  31. while (it.NextVisible(true))
  32. {
  33. if(it.name == "tags")
  34. {
  35. for (int i = 0; i < it.arraySize; i++)
  36. {
  37. SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
  38. if(string.IsNullOrEmpty(dataPoint.stringValue)){
  39. dataPoint.stringValue = tag;
  40. tagManager.ApplyModifiedProperties();
  41. return;
  42. }
  43. }
  44. }
  45. }
  46. }
  47. }
  48.  
  49. static void AddLayer(string layer)
  50. {
  51. if(!isHasLayer(layer))
  52. {
  53. SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
  54. SerializedProperty it = tagManager.GetIterator();
  55. while (it.NextVisible(true))
  56. {
  57. if(it.name.StartsWith("User Layer"))
  58. {
  59. if(it.type == "string" )
  60. {
  61. if(string.IsNullOrEmpty(it.stringValue)){
  62. it.stringValue  = layer;
  63. tagManager.ApplyModifiedProperties();
  64. return;
  65. }
  66. }
  67. }
  68. }
  69. }
  70. }
  71.  
  72. static bool isHasTag(string tag)
  73. {
  74. for (int i = 0; i < UnityEditorInternal.InternalEditorUtility.tags.Length; i++) {
  75. if (UnityEditorInternal.InternalEditorUtility.tags[i].Contains(tag))
  76. return true;
  77. }
  78. return false;
  79. }
  80.  
  81. static bool isHasLayer(string layer)
  82. {
  83. for (int i = 0; i < UnityEditorInternal.InternalEditorUtility.layers.Length; i++) {
  84. if (UnityEditorInternal.InternalEditorUtility.layers[i].Contains(layer))
  85. return true;
  86. }
  87. return false;
  88. }
  89. }