简体   繁体   English

如何从 Unity 上的 C# static class 获取当前文件夹

[英]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:我导入了一个 Unity package,其中几个编辑器脚本依赖于 static class 的RootPath属性:

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.问题是该路径是硬编码的,因此 package 位置根本无法更改。 I plan on changing the RootPath property so that it gets the current script location and searches for parent folder with a given pattern.我计划更改RootPath属性,以便它获取当前脚本位置并搜索具有给定模式的父文件夹。 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).这样,即使在我自己的自定义 package 中(即在 Packages 文件夹而不是 Assets 文件夹中),我也可以使用这个 package。

The missing piece is that I can't find a way to get this static class folder location from code.缺少的部分是我找不到从代码中获取此 static class 文件夹位置的方法。 Can anyone help me with this?谁能帮我这个?

Dig around through the AssetDatabase and find a reference to your script.挖掘 AssetDatabase 并找到对您的脚本的引用。 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.请记住将EditorUtils更改为您的脚本名称。

Here's the relevant Unity docs. 这是相关的 Unity 文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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