- Home /
How can I destroy a gameobject that is part of a prefab ?
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
public class ObjectsReplace : MonoBehaviour
{
public GameObject prefabToInit;
// Note your method should probably return something
public void UpdateOrAddShaderPrefabToDoors()
{
GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
GameObject[] doorsRight = GameObject.FindGameObjectsWithTag("Door_Right");
List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();
allDoors.ForEach(gameObject =>
{
Transform childTransform = gameObject.transform.Find("DoorShieldFXLocked Variant");
GameObject child = childTransform?.gameObject;
Debug.Log($"Child exist: {child != null}, Name of child: {child?.name}");
if (child != null)
{
ModifyPrefab(child);
}
});
}
private void ModifyPrefab(GameObject child)
{
var mostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(child);
// Get the Prefab Asset root GameObject and its asset path.
string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(mostPrefabInstanceRoot);
// Load the contents of the Prefab Asset.
GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);
PrefabUtility.UnpackPrefabInstance(mostPrefabInstanceRoot, PrefabUnpackMode.Completely, UnityEditor.InteractionMode.AutomatedAction);
// Modify Prefab contents.
DestroyImmediate(child);
// Save contents back to Prefab Asset and unload contents.
PrefabUtility.SaveAsPrefabAsset(mostPrefabInstanceRoot, assetPath);
PrefabUtility.UnloadPrefabContents(contentsRoot);
}
}
For some reason now the method ModifyPrefab change the prefabs in the Hierarchy to regular gameobjects. Luck I did a backup.
I tried to play with the ModifyPrefab and in some cases it's still give me the exception that I can't destroy a child that is part of prefab.
What I want to do is like in the editor Overrides > Apply Changes after make changes to prefab/s But I can't make it work in the script. The ModifyPrefab method should be the Overrides > Apply changes
The main goal is to destroy the childs and apply the changes.
Not sure but i think your problem is that you use "saveasprefabAsset" which creates a new asset ins$$anonymous$$d of applying the changes. There is another function with "applyprefabinstance" or something similar.
Your answer
Follow this Question
Related Questions
Link GUIText to a prefab? 2 Answers
Prefabs & Instances 1 Answer
Prefabs spawn with wrong values 0 Answers
Does my script have a memory leak ? 0 Answers
How do you destroy a prefab, but not the original object? 1 Answer