using System.Collections.Generic; using UnityEngine; using UnityEditor; public class PrefabHelper { [InitializeOnLoadMethod] static void StartInitializeOnLoadMethod() { PrefabUtility.prefabInstanceUpdated += OnPrefabInstanceUpdate; } static void OnPrefabInstanceUpdate(GameObject instance) { string path = UnityEditor.PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(instance); var rootGO = PrefabUtility.LoadPrefabContents(path); var prefabLoaders = rootGO.GetComponentsInChildren(); var dirty = false; foreach (var loader in prefabLoaders) { if (!string.IsNullOrEmpty(loader.prefabName)) { var children = new List(); for (int i = 0; i < loader.transform.childCount; i++) { children.Add(loader.transform.GetChild(i)); } for (int i = children.Count - 1; i >= 0; i--) { if (children[i].name == loader.prefabName) { var childGo = children[i].gameObject; GameObject.DestroyImmediate(childGo, true); DebugEx.LogFormat("保存预制:{0},删除了:{1}", path, loader.prefabName); dirty = true; } } } } if (dirty) PrefabUtility.SaveAsPrefabAsset(rootGO, path); PrefabUtility.UnloadPrefabContents(rootGO); } }