当一个项目打包为unityPackage后,再次导入其他项目后,项目里自定义的tag和layer会丢失,下面方法,在导入unitypackage包的时候自动把它的tag或者layer写进用户的项目里。将下面的脚本,随着资源一起打包,这样当别的工程导入该项目的unitypackage包时,程序会调用AddTag和AddLayer来添加,项目中可能已经添加了tag和layer,所以在添加前先做了判断。
转自MOMO,原文地址 : http://www.xuanyusong.com/archives/3169
下面代码只添加了一个tag和一个layer,修改添加N多个tag和layer
将该脚本放在工程下即可
using System;
using System.Collections;
using System.Reflection;
using UnityEditor;
using UnityEngine;
public class NewBehaviourScript : AssetPostprocessor
{
private static string[] myTags = { "aaaa", "bbbb", "cccc", "dddd"};
private static string[] myLayers = { "AAAA", "BBBB", "CCCC", "DDDD"};
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
foreach (string s in importedAssets)
{
if (s.Equals("Assets/NewBehaviourScript.cs"))
{
foreach (string tag in myTags)
{
AddTag(tag);
}
foreach (string layer in myLayers)
{
AddLayer(layer);
}
AddTag("self");<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">//增加一个叫self的tag</span>
AddLayer("self");<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">//增加一个叫ruoruo的layer</span>
return;
}
}
}
static void AddTag(string tag)
{
if (!isHasTag(tag))
{
SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
SerializedProperty it = tagManager.GetIterator();
while (it.NextVisible(true))
{
if (it.name == "tags")
{
for (int i = 0; i < it.arraySize; i++)
{
SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
if (string.IsNullOrEmpty(dataPoint.stringValue))
{
dataPoint.stringValue = tag;
tagManager.ApplyModifiedProperties();
return;
}
}
}
}
}
}
static void AddLayer(string layer)
{
if (!isHasLayer(layer))
{
SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
SerializedProperty it = tagManager.GetIterator();
while (it.NextVisible(true))
{
if (it.name.StartsWith("User Layer"))
{
if (it.type == "string")
{
if (string.IsNullOrEmpty(it.stringValue))
{
it.stringValue = layer;
tagManager.ApplyModifiedProperties();
return;
}
}
}
}
}
}
static bool isHasTag(string tag)
{
for (int i = 0; i < UnityEditorInternal.InternalEditorUtility.tags.Length; i++)
{
if (UnityEditorInternal.InternalEditorUtility.tags[i].Contains(tag))
return true;
}
return false;
}
static bool isHasLayer(string layer)
{
for (int i = 0; i < UnityEditorInternal.InternalEditorUtility.layers.Length; i++)
{
if (UnityEditorInternal.InternalEditorUtility.layers[i].Contains(layer))
return true;
}
return false;
}
}
转自MOMO,原文地址 : http://www.xuanyusong.com/archives/3169