Website may be up and down over next few months. I'm currently doing a complete overhaul of everything. Going back to simple individual .htm pages, new overall site theme, sanitizing and cleaning up html of all pages and blog posts, attempting to implement a new tooling and publishing system etc etc.

Below is a simple bit of code that will attempt to retrieve the asset path of the prefab stored on disk. The method will also try to walk up the prefab hierarchy if the prefab parameter appears to be a instance of the original. 

/// <summary>
/// Gets the source path to a prefab if any.
/// </summary>
/// <param name="prefab">The prefab reference to get the asset path for.</param>
/// <returns>Returns a asset path for a prefab.</returns>
/// <remarks>This method will attempt to find the source asset of the given <see cref="UnityEngine.Object"/> by 
/// walking up the parent prefab hierarchy.</remarks>
public static string GetSourcePrefab(UnityEngine.Object prefab)
{
    // if no prefab specified then return null
    if (prefab == null)
    {
        return null;
    }

    // attempt to get the path
    var path = AssetDatabase.GetAssetPath(prefab);

    // if no path returned it may be an instantiated prefab so try to get the parent prefab
    while (String.IsNullOrEmpty(path))
    {
        // try parent prefab
        var parent = PrefabUtility.GetPrefabParent(prefab);
                
        // no parent so must be generated through code so just exit loop
        if (parent == null)
        {
            break;
        }

        // attempt to get path for 
        path = AssetDatabase.GetAssetPath(parent);

        // set prefab reference to parent for next loop
        prefab = parent;
    }

    // return the path if any
    return path;
}

Add comment



biuquote
  • Comment
  • Preview
Loading






Created by: X

Just another personal website in this crazy online world

Name of author Dean Lunz (aka Created by: X)
Computer programming nerd, and tech geek.
About Me -- Resume