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

时间:2014-11-13 07:52:21

标签: c# unity3d texture2d

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

Assets/CaseSensitivePath/TextureName
CaseSensitivePath/TextureName
Assets/CaseSensitivePath/TextureName.png
CaseSensitivePath/TextureName.png

每次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;
        }
    }
}

错误:

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)

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

1 个答案:

答案 0 :(得分:4)

您不一定需要路径。您只需输入

即可
Resources.Load<Texture2D>("TextureName");

如果TextureName位于文件夹中,则输入:

Resources.Load<Texture2D>("MyFolder/TextureName");

如果您想使用Resources.Load,则需要将资源放在资源文件夹中。这就是它在编辑器中的样子。

enter image description here