Why does Resources.Load return null?

2020-05-21 09:04发布

My project has multiple sprites located in Assets\Sprites which I want to load using C# script.

I have tested this:

Sprite myFruit = Resources.Load <Sprite> ("Graphics_3");

But myFruit is still null.

7条回答
仙女界的扛把子
2楼-- · 2020-05-21 09:25
    Sprite sp = Resources.LoadAll<Sprite> ("Sprites/AI-Avtar") [2] as Sprite;
查看更多
贪生不怕死
3楼-- · 2020-05-21 09:30

Resources.Load are searching in the directory "Assets/Resources" That's why you need to do

_sprites = Resources.LoadAll<Sprite>(spritesPath);

or

_sprites = Resources.Load<Sprite>(spritesPath);

with spritesPath as relative path. If you need to load all from folder "Assets/Resources/Sprites", you need to write only "Sprites".

after this you can just do the following:

var sprite = sprites[0];

or

var sprite = _sprites.Where(a => a.name == "Sprite_Name_Needed").First();
查看更多
SAY GOODBYE
4楼-- · 2020-05-21 09:31

I just used Resources.Load to load my sprite and found the result is Texture2D. So I Use Sprite.Create to create a new sprite with Textur2D to fix this problem.

查看更多
疯言疯语
5楼-- · 2020-05-21 09:33

You need to enter the full path for the asset. In this case, try using the path "Sprites/Graphics_3".

查看更多
\"骚年 ilove
6楼-- · 2020-05-21 09:34

Resources.Load will search for a directory in Assets/Resources.

If you want to put it to Sprites directory then put it inside Resources (ex. Assets/Resources/Sprites).

Then you can just load it like this:

Sprite myFruit = Resources.Load <Sprite> ("Sprites/Graphics_3");

Also make sure that you've set your image type to Sprite in the inspector.

If you want to load multiple sprites, use this:

Sprite[] myFruit = Resources.LoadAll <Sprite> ("Sprites/Graphics_3");  

See this for more details.

查看更多
贼婆χ
7楼-- · 2020-05-21 09:39

Place awesome.png in Assets/Resources/ (you can have subfolders), and use:

GetComponent<SpriteRenderer>().sprite = 
    Resources.Load<Sprite>("awesome");  // No file extension.

http://docs.unity3d.com/ScriptReference/Resources.html

There's also LoadAll that "Loads all assets in a folder or file at path in a Resources folder."

查看更多
登录 后发表回答