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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With