Changing sprites at runtime without Resource.Load?

Hi all

I’ve been using unity for a while now but I’m pretty new to the canvas system (been using 2D Toolkit for UI up until now).

I have some interface elements that change sprites pretty often, like inventory grids and enemy profile icons. It seems that the only way to load up sprites at runtime is by either:

  1. Using Resource.Load: I’ve always avoided using because it’s considered slow and bad practice at runtime.
  2. Dragging the sprites into public properties in the editor beforehand and then accessing them via code. Works for simple sprites/objects, but doesn’t work for elements that are created at runtime (for example, it’s not like I’m going to make a public property for every inventory item in the game).

In 2D toolkit I have a sprite collection where I can reference everything at runtime via it’s sprite ID and switch them around whenever needed. Is there anyway to get access to the sprites that Unity already loaded in its sprite atlas? At the moment if I need to load up an inventory with 50 items, doesn’t that mean 50 Resource.Load calls? Should I just be manually making a bunch of Resource.Load calls at the start of the game and then caching the references?

Cheers.

You can’t use a Unity sprite atlas with Resources.Load in any case; it doesn’t work (by design). There’s no access to a Unity sprite atlas, since the system is designed to work behind the scenes and handle it for you, so it’s not necessary to fiddle with atlasses. You can just use an array of sprites.

public Sprite[] inventoryItems;

If you don’t want to do it manually, you can write editor scripts to populate variables via code.

–Eric

Thanks Eric, that’s what I suspected. I’ll add a loading script that spins up all this stuff at the start - just wanted to make sure I wasn’t missing some obvious API call to the atlas or something first.

Cheers.