Search Unity

Convert Absolute Filename To Package Relative

Discussion in 'Scripting' started by neil_sublime, Apr 12, 2019.

  1. neil_sublime

    neil_sublime

    Joined:
    Jul 9, 2018
    Posts:
    17
    Is there a way to convert an absolute path into one that's relative to a package, so it can be used with the AssetDatabase?

    For example, convert "C:/Work/SomePackage/SomeFile.cs" into "Packages/somepackage/SomeFile.cs".

    My project uses a few local packages (libraries that we've created in-house). One of our debugging tools is trying to use AssetDatabase::LoadAssetAtPath() and OpenAsset() to open the source code in the editor.

    The AssetDatabase doesn't like absolute filenames however, and wants them to start with "Assets/" or "Packages/". I can easily convert a filename into one relative to "Assets/", but not for "Packages/".

    I tried using the PackageManager.Client API to get a list of packages and manually figure out which package the file belongs to, but that API is asynchronous and doesn't fit my needs.
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    If you make some assumptions, such as the last index of "Assets" being the project's root or the first index of your project's name, you can do it with a simple substring. I'm not sure how flexible you need it to be.
     
  3. Ejlersen

    Ejlersen

    Joined:
    Apr 30, 2009
    Posts:
    11
    Currently, I have this. If it helps anyone.

    Code (CSharp):
    1. private static string ToRelativePath(string path)
    2. {
    3.     var info = new FileInfo(path);
    4.     string absPath = info.FullName;
    5.     string[] arr = AssetDatabase.GetAllAssetPaths();
    6.  
    7.     for (var i = 0; i < arr.Length; i++)
    8.     {
    9.         info = new FileInfo(arr[i]);
    10.  
    11.         if (info.FullName.Equals(absPath))
    12.             return arr[i];
    13.     }
    14.  
    15.     return string.Empty;
    16. }