Search Unity

How to detect if we are in a packager context or in the Assets folder

Discussion in 'Package Manager' started by Jean-Fabre, May 27, 2021.

  1. Jean-Fabre

    Jean-Fabre

    Joined:
    Sep 6, 2007
    Posts:
    429
    Hi,

    I am wondering how I can check from code if I am inside a package, instead of inside the Assets Folder.

    I need to know because some editor scripts needs to load assets by path, and it's different if you are inside a package then inside the assets.

    Right now, the only way I found is to find the path of the script instance like this:

    string _pathtoSelf = AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(Instance));

    if (_pathtoSelf.StartsWith("Packages"))
    {
    // I am inside a package
    }else
    {
    // I am inside the Assets
    }

    It works, but I hope for an actual api provided by Unity to check on this instead of hacking around :)

    Thanks,

    Jean
     
  2. maximeb_unity

    maximeb_unity

    Unity Technologies

    Joined:
    Mar 20, 2018
    Posts:
    555
    Hi @Jean-Fabre,

    If you want to check this from a script whose location is not known upfront, you can dynamically check using the following code snippet:
    Code (CSharp):
    1. var assembly = System.Reflection.Assembly.GetExecutingAssembly();
    2. var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssembly(assembly);
    3. if (packageInfo != null)
    4. {
    5.     Debug.Log("In package " + packageInfo.name);
    6. }
    7. else
    8. {
    9.     Debug.Log("Not in package");
    10. }
    11.  
     
    darbotron and Jean-Fabre like this.
  3. maximeb_unity

    maximeb_unity

    Unity Technologies

    Joined:
    Mar 20, 2018
    Posts:
    555
    Note that this relies on Editor-only APIs, so you cannot use this code in a Player build. If that's your case, you would need to compute this during the build and generate some asset that contains this information and include that asset in the build. But I see you used the AssetDatabase.GetAssetAtPath method in your own workaround, which is an Editor-only API too, so I don't think this should be a problem for your use case.
     
  4. Jean-Fabre

    Jean-Fabre

    Joined:
    Sep 6, 2007
    Posts:
    429
    Hi,

    The package I am developing is Editor only, so that will work, but I am going to stick to my hack, cause I anyway need it for other reasons.

    but still... it's such an obvious things to have in the api and we have to hack around. Please consider implementing this, this basics api context requirements... since we have now two very distinct Context ( assets, Packages) I think it's important to conveniently provide a way to make this distinction.

    Bye,

    Jean
     
    mattstromaneveri likes this.
  5. darbotron

    darbotron

    Joined:
    Aug 9, 2010
    Posts:
    352
    Life saver! Thanks for this gem :D