Search Unity

  1. All Pro and Enterprise subscribers: find helpful & inspiring creative, tech, and business know-how in the new Unity Success Hub. Sign in to stay up to date.
    Dismiss Notice
  2. Dismiss Notice

Help Wanted How to get corresponding object from loaded content?

Discussion in 'Prefabs' started by Aka_ToolBuddy, May 9, 2021.

  1. Aka_ToolBuddy

    Aka_ToolBuddy

    Joined:
    Feb 25, 2014
    Posts:
    301
    Hi

    My goal is to delete from a prefab a specific object. I use the following code to do so:

    Code (CSharp):
    1. GameObject objectToDestroy = ...; //my input
    2. string prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(objectToDestroy);
    3. GameObject prefabContentsRoot = PrefabUtility.LoadPrefabContents(prefabPath);
    4.  
    5. GameObject correspondingObject = ...;//Find in prefabContentsRoot the object corresponding to objectToDestroy
    6.  
    7. DestroyObject(correspondingObject );
    8.  
    9. PrefabUtility.SaveAsPrefabAsset(prefabContentsRoot, prefabPath);
    10. PrefabUtility.UnloadPrefabContents(prefabContentsRoot);
    For now, I find the corresponding object by comparing names, but this is of course not a safe way (multiple objects can have the same name in the same prefab).
    I tried using the PrefabUtility.GetCorrespondingObjectXXX methods, but they return an object that is part of the prefab asset, and not part of the prefab loaded content. So I guess I need a PrefabUtility.GetCorrespondingObjectFromInstance(prefabContentsRoot, objectToDestroy), but such method does not seem to exist. How should I do?

    Thanks
     
  2. pietrodenicola

    pietrodenicola

    Unity Technologies

    Joined:
    Dec 8, 2020
    Posts:
    25
    Hi. Currently there is no API for finding objects and the only way is relying on the name.
     
    Aka_ToolBuddy likes this.
unityunity