简体   繁体   中英

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

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
    {
        get
        {
            return "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?

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM