By default, Unity will strip all files that aren’t required to make a build smaller. But what happens if you want to load resources by name in runtime? Enter the Resources Folder.

My first use of this folder was in creating icons to show the wind in my upcoming ship trading game. I wanted to load these by name, as the wind patterns are quite random, and they each know their wind. The objects that store the state of the wind don’t have access to resources, and in any case, I didn’t want to drag a large number of resources into the game object.

The key to this is to put all of your resources into a folder named “Resources”. I suggest you further group them. As you can see, these are the “Wind” objects. These are prefabs, used to ensure the size and direction is correct for each object.

There are a number of ways to load them. I like to use the “Resources.LoadAll”, which will load all of the items in a folder, but you could manually specify. This is the code I used to load these resources

GameObject[] winds = Resources.LoadAll<GameObject>("Wind");
Dictionary<string, GameObject> windDirectionGO = new Dictionary<string, GameObject>();
foreach (GameObject wind in winds)
{
    windDirectionGO.Add(wind.name, wind);
}

Note that I stored them in a dictionary, so I could easily pick out the wind direction I wanted. So, what do you do about images? Well, here’s an example of the code to load .PNG files

nameToTexture = new Dictionary<string, Texture>();
Texture[] holdSprites = Resources.LoadAll<Texture>("Sprites/Hold");
foreach (Texture sprite in holdSprites)
{
    nameToTexture.Add(sprite.name, sprite);
}

Both sprites and GameObjects have a .name field, which has the name of the objects.

For alternative ways, see the Unity Resources Documentation.

About the Author:

Ben Pearson is the author of the Amateur Radio and other technology blog KD7UIY anddeveloper of Games and Apps at Google Play pearsonartphoto, where he plans to publish some of the games created by inspiration of gamedev.tv. He is currently working on a Sea Trading game, which you can subscribe to updates at his Google Group. He has been a programmer since a young age, although only recently is learning programming with game engines. He has completed the the Complete Unity Developer Course and the Procedural Generation courses, and is working through the Complete Blender Developer Course and Unity Game Physics courses. He is hoping to soon start Unreal Courses soon. Follow him on Twitter @KD7UIY.