How to get the path name of the object being inspected in the editor?

I have a prefab that has a set of child items, some of these children, need a set of assets in order to properly work. Each one of those items has and editor script that contains a button that triggers a process that creates the required assets when clicked. I would like to save these files on the same folder in which the prefab is located. I’m using the piece of code shown below to retrieve such path, but what I get is a empty string.

GameObject selected = (GameObject) Selection.activeObject;
string     fileName = AssetDatabase.GetAssetPath(selected.transform.root.GetInstanceID());

Log what you are working with.

Specifically make sure that transform.root is the object you think it is (the prefab root). If the instance is in a scene it may be a different object. The instance ID likewise may not be from an asset but an in-scene object. Note that you can pass the asset object instead just as well (ie the prefab root object).

Use the PrefabUtility to get more info about the prefab itself. For instance you could use IsPartOfPrefabAssset to ensure the object you’re dealing with is an actual prefab object.

And skipping ahead because I expect this is what’s going to happen if I don’t mention it: when you do AssetDatabase.CreateAsset you do NOT have to “Save” the created object nor do you need to Refresh the AssetDatabase. :wink:

Just for the record, I was skeptical ChatGPT could give me the answer to this as it first gave me the same answer I’ve seen in many forums, but after several attempts it finally got the right answer:

      PrefabStage ps    = PrefabStageUtility.GetPrefabStage(transform.root.gameObject);
      string      fname = ps.assetPath;

Thanks anyway, the question now is if we humans have became obsolete.

Not even when AI gets the right answer the first time every time. :stuck_out_tongue: