unity3d预制体修改与保存

给预制体添加子物体并保存,预期效果:

unity3d预制体修改与保存_第1张图片


public class GunFireMenuItems : MonoBehaviour
    {
        public static string effectPrefabPath = "Assets/MuzzleFlashes 1/";
        public static string effectOSXPath = "Assets/../StreamingAssets/OSX/GunFire/";
        public static string effectLinuxPath = "Assets/../StreamingAssets/Linux/GunFire/";

        [MenuItem ("Assets/AssetBundles/GunFire/AddGunFireEffectTag")]
        public static void AddGunFireEffectTag ()
        {
            EditorUtility.DisplayProgressBar ("Modify Prefab", "Please wait...", 0);
            var files = new DirectoryInfo (effectPrefabPath).GetFiles ();
            for (int i = 0; i < files.Length; i++) {
                var fileInfo = files [i];
                if (fileInfo.Name.EndsWith (".prefab")) {
                    //Debug.Log (effectPrefabPath + fileInfo.Name);
                    AddEffectTag (effectPrefabPath + fileInfo.Name); //添加effectTag
                    EditorUtility.DisplayProgressBar ("Modify Prefab", "Please waiti...", (i + 1) / (float)files.Length);
                }
            }
            AssetDatabase.SaveAssets ();
            //去除进度条
            EditorUtility.ClearProgressBar ();
        }

        /// 
        /// Adds the effect tag.
        /// 
        /// Prefab full path.
        public static void AddEffectTag (string prefabFullPath)
        {
            GameObject tempEffectPrefab = AssetDatabase.LoadAssetAtPath (prefabFullPath);
            GameObject tempEffectInstant = PrefabUtility.InstantiatePrefab (tempEffectPrefab) as GameObject;

            //没有EffectTag则添加
            foreach (Transform  trans in  tempEffectInstant.transform) {
                if (trans.name.Contains ("EffectTag")) {
                    DestroyImmediate (tempEffectInstant);
                    return;
                }
            }

            GameObject EffectTag = new GameObject ("EffectTag");
            GameObject Gunfire = new GameObject ("Gunfire");
            Gunfire.transform.parent = EffectTag.transform;
            EffectTag.transform.parent = tempEffectInstant.transform;

            //替换保存
            PrefabUtility.ReplacePrefab (tempEffectInstant, tempEffectPrefab, ReplacePrefabOptions.ConnectToPrefab);
            DestroyImmediate (tempEffectInstant);
        }
    }

你可能感兴趣的:(Unity3D)