How to get current folder from a C# static class on Unity

Viewed 2008

I imported a Unity package where several Editor scripts depend on a RootPath property from a static class:

public static class EditorUtils
{
    public static string RootPath => "Assets/HardcodedPath";
}

The problem is that this path is hardcoded, so that the package location can't be changed at all. I plan on changing the RootPath property so that it gets the current script location and searches for parent folder with a given pattern. That way, I would be able to use this package even inside a custom package of my own (inside a Packages folder instead of the Assets folder, that is).

The missing piece is that I can't find a way to get this static class folder location from code. Can anyone help me with this?

1 Answers

Dig around through the AssetDatabase and find a reference to your script. This should return what you're wanting.

public static class EditorUtils
{
    public static string RootPath
    {
        get
        {
            var g = AssetDatabase.FindAssets ( $"t:Script {nameof(EditorUtils)}" );
            return AssetDatabase.GUIDToAssetPath ( g [ 0 ] );
        }
    }
}

That will also hold true for scripts in Packages. Remember to change EditorUtils to your script name.

Here's the relevant Unity docs.

Related