Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Resources.Load <Sprite> return null?

Tags:

c#

unity3d

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.

like image 496
Brian Nguyen Avatar asked Jul 27 '14 04:07

Brian Nguyen


3 Answers

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.

like image 126
Jay Kazama Avatar answered Nov 12 '22 12:11

Jay Kazama


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."

like image 20
Anis Abboud Avatar answered Nov 12 '22 14:11

Anis Abboud


I know this is an old post but, if it still does not work by just loading the resources, then we have to add the texture as well. I did it in this way.

Texture2D texture = Resources.Load<Texture2D>("Sprites/imageName");
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
btnImage.image.sprite = sprite;
like image 1
apex Avatar answered Nov 12 '22 14:11

apex