Search Unity

DestroyImmediate in Prefab Mode

Discussion in 'Prefabs' started by Say-Chimp, Aug 22, 2019.

  1. Say-Chimp

    Say-Chimp

    Joined:
    Jul 16, 2019
    Posts:
    2
    I am having an editor code that have inconsistent behavior.

    Code (CSharp):
    1.  
    2.     private void ClearAllDecosInternal()
    3.     {
    4.         GetAllWalls();
    5.  
    6.         for (int i = 0; i < _wallsInLevel.Count; i++)
    7.         {
    8.             /*
    9.              * Inconsistent behaviour -_-
    10.             if (PrefabUtility.IsPartOfPrefabInstance(_wallsInLevel[i].transform.parent.gameObject))
    11.             {
    12.                 PrefabUtility.UnpackPrefabInstance(_wallsInLevel[i].transform.parent.gameObject, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
    13.             }
    14.             */
    15.             _wallsInLevel[i].GetComponent<WallScript>().ClearAllDecorations();
    16.         }
    17.  
    18.         MarkChangesToPrefab();
    19.     }
    20.  
    Code (CSharp):
    1.  
    2.     public void ClearAllDecorations()
    3.     {
    4.         Transform[] childs = gameObject.GetComponentsInChildren<Transform>();
    5.         List<GameObject> decos = new List<GameObject>();
    6.         for (int i = 0; i < childs.Length; i++)
    7.         {
    8.             if (childs[i].CompareTag("WallDeco"))
    9.             {
    10.                 decos.Add(childs[i].gameObject);
    11.             }
    12.         }
    13.  
    14.         for (int i = 0; i < decos.Count; i++)
    15.         {
    16.             if (decos != null)
    17.             {
    18.                 DestroyImmediate(decos[i].gameObject);
    19.             }
    20.         }
    21.     }
    22.  
    It works for some of prefabs and breaks for some prefabs.
    The error thrown by editor is
    InvalidOperationException: Destroying a GameObject inside a Prefab instance is not allowed.
    .

    To answer a few questions, the walls are prefabs. The Decorations are prefab. My issue is why it works on some prefabs, and not on another. I dont want to unpack the prefab because, i want to be able to use the nested prefab feature.
     
  2. Say-Chimp

    Say-Chimp

    Joined:
    Jul 16, 2019
    Posts:
    2
    I used a workaround that worked for me.
    PrefabUtility.RevertPrefabInstance