Search Unity

How to get prefab path from prefab game object?

Discussion in 'Prefabs' started by quabug, Jan 13, 2020.

  1. quabug

    quabug

    Joined:
    Jul 18, 2015
    Posts:
    66
    Code (CSharp):
    1. [InitializeOnLoad]
    2. public static class SavePrefabFile
    3. {
    4.     static SavePrefabFile()
    5.     {
    6.         PrefabStage.prefabSaved += OnPrefabSaved;
    7.     }
    8.  
    9.     static void OnPrefabSaved(GameObject prefab)
    10.     {
    11.         // path is empty? how can I get the right path from prefab?
    12.         var path = AssetDatabase.GetAssetPath(prefab);
    13.     }
    14. }
    15.  
     
  2. quabug

    quabug

    Joined:
    Jul 18, 2015
    Posts:
    66
    it must be something wrong with `PrefabStage.prefabSaved` callback, since `PrefabUtility.prefabInstanceUpdated` works well.

    Code (CSharp):
    1.         static SavePrefabFile()
    2.         {
    3.             // PrefabStage.prefabSaved -= OnPrefabSaved;
    4.             // PrefabStage.prefabSaved += OnPrefabSaved;
    5.             PrefabUtility.prefabInstanceUpdated += OnPrefabSaved;
    6.         }
    7.  
    8.         static void OnPrefabSaved(GameObject prefab)
    9.         {
    10.             // all those value were null if use callback of `PrefabState.prefabSaved`
    11.             var PrefabInstanceHandle = PrefabUtility.GetPrefabInstanceHandle(prefab);
    12.             var CorrespondingObjectFromSource = PrefabUtility.GetCorrespondingObjectFromSource(prefab);
    13.             var OutermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(prefab);
    14.             var NearestPrefabInstanceRoot = PrefabUtility.GetNearestPrefabInstanceRoot(prefab);
    15.             var CorrespondingObjectFromOriginalSource = PrefabUtility.GetCorrespondingObjectFromOriginalSource(prefab);
    16.             var path = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(prefab);
    17.         }
    18.  
     
  3. akrimahuzaifa

    akrimahuzaifa

    Joined:
    Nov 8, 2020
    Posts:
    2
    Code (CSharp):
    1.     void Start()
    2.     {
    3. #if UNITY_EDITOR
    4.         // Assuming you have a reference to the prefab game object
    5.         GameObject prefabGameObject = gameObject;
    6.  
    7.         // Get the prefab path
    8.         string prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(prefabGameObject);
    9.  
    10.         Debug.Log("Prefab Path: " + prefabPath);
    11. #endif
    12.     }
     
    Last edited: Jul 5, 2023
  4. Mads-Nyholm

    Mads-Nyholm

    Unity Technologies

    Joined:
    Aug 19, 2013
    Posts:
    219
    @quabug

    Try:
    Code (CSharp):
    1.     static void OnPrefabSaved(GameObject prefabRoot)
    2.     {
    3.         var prefabStage = (PrefabStage)StageUtility.GetStage(prefabRoot);
    4.         var path = prefabStage.assetPath;
    5.     }