什么是正确的 Resource.Load 路径?

Tom*_*ica 3 c# texture2d unity-game-engine

我正在尝试Texture2D使用 .png加载(.png) 资源Resource.Load。我试过以下路径模式:

Assets/CaseSensitivePath/TextureName
CaseSensitivePath/TextureName
Assets/CaseSensitivePath/TextureName.png
CaseSensitivePath/TextureName.png
Run Code Online (Sandbox Code Playgroud)

每次都Resource.Load(path, typeof(Texture2D))返回null。这是我的代码和错误处理:

public class LazyResource<T> where T : UnityEngine.Object
{

    //Path is read-only
    public string path { get { return _path; } }
    private string _path = "";
    //Whether NOT FOUND warning was thrown
    //in that case, further load attemts are ommited and the resource returns always null...
    public bool failed = false;
    //Constructor uses the path as first parameter
    public LazyResource(string path) {
        _path = path;
    }
    //Cached resource
    private T cache = null;

    public T res
    {
        get
        {
            //Does not re-try if it failed before
            if (cache == null && !failed)
            {
                //Load the proper type of resource
                cache = (T)Resources.Load(_path, typeof(T));
                //Throw warning (once)
                if (cache == null)
                {
                    Debug.LogWarning("Icon not found at '" + _path + "'!");
                    failed = true;
                }
            }
            //Can return null
            return cache;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

Icon not found at 'Textures/GUI/Build/egg'!
UnityEngine.Debug:LogWarning(Object)
LazyResource`1:get_res() (at Assets/WorldObject/LazyResource.cs:28)
Actions.Action:GetMenuIcon() (at Assets/WorldObject/Action.cs:203)
HUD:DrawActions(Action[]) (at Assets/Player/HUD/HUD.cs:115)
HUD:DrawOrdersBar() (at Assets/Player/HUD/HUD.cs:85)
HUD:OnGUI() (at Assets/Player/HUD/HUD.cs:63)
Run Code Online (Sandbox Code Playgroud)

在 Unity3D 项目中加载纹理的正确路径是什么?

Fun*_*onR 5

您不一定需要路径。你可以简单地输入

Resources.Load<Texture2D>("MyTexture");
Run Code Online (Sandbox Code Playgroud)

如果TextureName在文件夹中,则键入:

Resources.Load<Texture2D>("MyFolder/MyTexture");
Run Code Online (Sandbox Code Playgroud)

如果要使用,Resources.Load则需要将资源放在Resource 文件夹中。这是它在编辑器中的外观。

在此处输入图片说明

  • 如果你想使用`Resources.Load`,那么你需要把资源放在**Resource文件夹**中。 (2认同)
  • 对我来说,@apxcode 解决了这个问题...我真的只是觉得 Assets 文件夹就是为此而设计的,我的直觉是 `Resources.Load` 就是从 asset 加载。但不行:你必须手动创建一个资源文件夹。奇怪的教训。 (2认同)