Unity3d load sprite from Textures folder

12,871

Solution 1

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;

Solution 2

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.

Share:
12,871
filipst
Author by

filipst

Updated on July 13, 2022

Comments

  • filipst
    filipst almost 2 years

    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.