Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity3d load sprite from Textures folder

I have around 200 sprites (jpg pictures) in Assets>Textures>Pictures, and I have GameObject with <SpriteRenderer>. Is there a way for me to load sprites from that folder into this GameObject in code? Something like Resources.Load<Sprite>("path");

Thank you.

like image 241
filipst Avatar asked Jan 10 '23 08:01

filipst


2 Answers

Put your folder inside the Resources folder. Like this: Assets/Textures/Resources/

Then you can do this:

private Object[] textures;

void Awake()
{
    textures = Resources.LoadAll("Path");
}

You have to store them as Objects. However, if you want to use them later you can do something like this.

texture = textures[i] as Texture;
like image 149
apxcode Avatar answered Jan 12 '23 22:01

apxcode


Well, the solution is Resources.Load<Sprite>("path") for a single sprite or Resources.LoadAll<Sprite>("path") if you want to load them all at once.

In order to use these methods you need to move your sprites into a sub directory named "Resources", e.g, Assets/Textures/Pictures/Resources.

This and more information about the consequences of going this way are explained in more detail in the scripting reference:

All assets that are in a folder named "Resources" anywhere in the Assets folder can be accessed via the Resources.Load functions. Multiple "Resources" folders may exist and when loading objects each will be examined.

In Unity you usually don't use path names to access assets, instead you expose a reference to an asset by declaring a member-variable, and then assign it in the inspector. When using this technique Unity can automatically calculate which assets are used when building a player. This radically minimizes the size of your players to the assets that you actually use in the built game. When you place assets in "Resources" folders this can not be done, thus all assets in the "Resources" folders will be included in a build.

like image 23
Stefan Hoffmann Avatar answered Jan 12 '23 20:01

Stefan Hoffmann