5

I'm trying to load a Texture2D (.png) resource using Resource.Load. I've tried following path patterns:

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

Every time, Resource.Load(path, typeof(Texture2D)) returns null. This is my code and error handling:

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

Error:

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)

What is the correct path to load a texture in the Unity3D project?

apxcode
  • 7,696
  • 7
  • 30
  • 41
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778

1 Answers1

7

Create a Resources folder in your Assets folder:

Resources folder example

Then use Resources.Load():

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

Pikamander2
  • 7,332
  • 3
  • 48
  • 69
apxcode
  • 7,696
  • 7
  • 30
  • 41
  • 1
    It's in `Assets/GUI/Build/egg.png`. The problem is that I didn't know you must use [the Resources folder](http://answers.unity3d.com/questions/14748/c-resourcesload-problem.html)... That sucks. I want to organize my files as I will. – Tomáš Zato Nov 13 '14 at 08:14
  • 2
    If you want to use `Resources.Load` then you need to put the resource in the **Resource folder**. – apxcode Nov 13 '14 at 08:15
  • I'll use something different. – Tomáš Zato Nov 13 '14 at 08:19
  • 2
    For me @apxcode solved it... I really just felt Assets folder is for this, my intuition was `Resources.Load` was all about loading from assets. But no: you have to make a resources folder by hand. Strange lesson to learn. – Ákos Nikházy Oct 07 '20 at 15:26