Unity中要删除预制体中的某个子游戏物体,需要先将该预制体UnPack,然后调用DestroyImmediate删除GameObeject,然后再保存预制体。这其实挺麻烦的,因为有时你拿到的gameObject是Asset中的资源,将预制体实例化后不好找到实例中对应的gameObject,拿名字找可以,但还是会有重名的风险。
我的方法无论传入的gameObject是处于场景中的实例还是处于Asset中都可以删除:文章来源地址https://www.toymoban.com/news/detail-502909.html
//删除预制体中的某个GameObject,不论其是不是在场景中的instance
public static void DestroyGameObjectInPrefab(GameObject go)
{
if (PrefabUtility.IsPartOfAnyPrefab(go))
{
GameObject instance = null;
GameObject deleteObj = null;
bool isInAsset = EditorUtility.IsPersistent(go);
if (isInAsset)
{
//在asset中
var root = go.transform.root.gameObject;
instance = PrefabUtility.InstantiatePrefab(root) as GameObject;
deleteObj = GetCorrespondingGameObjectInInstance(instance.transform, go);
}
else
{
instance = PrefabUtility.GetOutermostPrefabInstanceRoot(go);
deleteObj = go;
}
string prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(instance);
PrefabUtility.UnpackPrefabInstance(instance, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
GameObject.DestroyImmediate(deleteObj);
PrefabUtility.SaveAsPrefabAsset(instance, prefabPath);
if(isInAsset)
GameObject.DestroyImmediate(instance);
}
}
public static GameObject GetCorrespondingGameObjectInInstance(Transform root, GameObject assetObj)
{
if (PrefabUtility.GetCorrespondingObjectFromOriginalSource(root.gameObject) == assetObj)
{
return root.gameObject;
}
foreach (Transform child in root)
{
var ret = GetCorrespondingGameObjectInInstance(child, assetObj);
if (ret != null)
return ret;
}
return null;
}
文章来源:https://www.toymoban.com/news/detail-502909.html
到了这里,关于Unity中删除预制体的子物体的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!