How can I get the full path to an object in an ObjectField?

I have an editor script in which you can choose textures and assign them to EditorGUILayout.ObjectFields. After the user has dragged textures(objects) into the object fields I’d like to know the paths of where they came from so I can perform other functions on them.

How is that done?


Path relative to project folder can be found using the following:

Object selectedObject = EditorGUILayout.ObjectField(selectedObject, typeof(Object));
if (selectedObject != null) {
    string assetPath = AssetDatabase.GetAssetPath(selectedObject);

Which will produce a string like:

"Assets/Some/Path/YourObject.prefab" (if you select a prefab)

You can then get the absolute path (if needed) using:

using System.IO;
string filePath = Path.Combine(Directory.GetCurrentDirectory(), assetPath);
// i.e. "/Your Unity Project/Assets/Some/Path/YourObject.prefab"

// The following is needed if you are using Windows :-)
filePath = filePath.Replace("/", "\\");
// i.e. "C:\Your Unity Project\Assets\Some\Path\YourObject.prefab"

You can use :

string path = AssetDatabase.GetAssetPath (myObject);

Note: path will be the full path to the object that has been dropped onto “myObject” objectfield.