Loading a Sprite (Unity 4.3) in resource folder and setting it in sprite renderer

Hey Guys,

I have a SpriteSheet which I imported in Unity so I have a basic Texture2D asset which is separated in multiple sprites which are named like (sprite_0,sprite_1, etc.) Im trying to set the sprite of my SpriteRenderer in code but I want to be able to load a sprite dynamically, not have to link it in the script directly. So I have a Resources and a Textures folder within it. I’ trying to get the sprite by doing Sprite s = Resources.Load(“Textures/sprite_0”) as Sprite. But it is always null. In fact, when I want to load the “Base” sprite named “Sprite”, it recognize it as a Texture2D type, but when I want to load a specific sprite in my texture like sprite_0, it just can’t find it at all. I have my texture type set to Sprite, and Mode to multiple. Does anybody have an idea ?. Thanks a lot for your time :slight_smile:

Claude

Sprite sprites = Resources.LoadAll(“Textures”);

For multi-sprite textures I found this to work:

UnityEngine.Object allSprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(“Assets/Textures/” + SpriteTextureName + TextureExtension);

You can also define sprites in advance.

public Sprite[] sprites;

Then you can bind sprites in Unity Editor, and set SpriteRenderer.sprite in runtime like this.

SpriteRenderer sr = GetComponent<SpriteRenderer>();
sr.sprite = this.sprites[Random.Range(0, this.sprites.GetLength(0) - 1)];

For some situation this is enough.

I hope this can help.

Regards.

You can use System.Linq to find easily sprite into texture :wink:

For example:

private Sprite GetLevelSprite(string textureName)
        {
            Sprite[] textures = Resources.LoadAll<Sprite>("MySpriteSheet");
            return textures.Where(t => t.name == textureName).First<Sprite>();       
        }

GetLevelSprite("plop") will return the sprite with /Assets/Resources/MySpriteSheet/plop path :wink:

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();