Search Unity

How can I destroy an object that is in a prefab and part of the prefab ?

Discussion in 'Editor & General Support' started by Chocolade, Feb 16, 2020.

  1. Chocolade

    Chocolade

    Joined:
    Jun 19, 2013
    Posts:
    933
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using UnityEditor;
    6. using UnityEngine;
    7.  
    8. public class ObjectsReplace : MonoBehaviour
    9. {
    10.     public GameObject prefabToInit;
    11.  
    12.     // Note your method should probably return something
    13.     public void UpdateOrAddShaderPrefabToDoors()
    14.     {
    15.         GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
    16.         GameObject[] doorsRight = GameObject.FindGameObjectsWithTag("Door_Right");
    17.  
    18.         List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();
    19.  
    20.         allDoors.ForEach(gameObject =>
    21.         {
    22.             Transform childTransform = gameObject.transform.Find("DoorShieldFXLocked Variant");
    23.             GameObject child = childTransform?.gameObject;
    24.             Debug.Log($"Child exist: {child != null}, Name of child: {child?.name}");
    25.             if (child != null)
    26.             {
    27.                 //ModifyPrefab(child);
    28.             }
    29.         });
    30.     }
    31.  
    32.     private void ModifyPrefab(GameObject child)
    33.     {
    34.         var mostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(child);
    35.  
    36.         // Get the Prefab Asset root GameObject and its asset path.
    37.         string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(mostPrefabInstanceRoot);
    38.  
    39.         // Load the contents of the Prefab Asset.
    40.         GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);
    41.  
    42.         // Modify Prefab contents.
    43.         DestroyImmediate(child);
    44.  
    45.         // Save contents back to Prefab Asset and unload contents.
    46.         PrefabUtility.SaveAsPrefabAsset(mostPrefabInstanceRoot, assetPath);
    47.         PrefabUtility.UnloadPrefabContents(mostPrefabInstanceRoot);
    48.     }
    49. }
    50.  
    I'm trying to do the same in the editor : Overrides > Apply Changes

    But I'm still getting exception in the console on the line :

    Code (csharp):
    1.  
    2. DestroyImmediate(child);
    3.  
    You can't destroy object that is part of prefab.

    Another problem is in one of my tests when changing the code it's changed the prefabs to regular objects.
    Lucky I did a backup but not sure why it's changed the prefabs in the hierarchy to regular gameobjects.