Loading Assets at Run Time
What use is this?
In Unity, most assets are assigned while working in the scene view. An example is when a texture is assigned to an object or an asset is dropped into a slot on a script in the inspector. This is how Unity determines which assets it has to have loaded at any given time and determines which assets are included in a build. However, there are times when loading assets into the inspector can be tedious or inappropriate.
For example, if a single character has many 50 outfits that are implemented as alternate textures, then loading all 50 textures into the inspector becomes tedious and a waste of memory, as Unity will load all 50 textures into memory. An alternative approach is to load the outfit at the start of the game and then unload the rest of the textures. This allows the game to reclaim unused memory and run more smoothly.
A Simple Example:
In this example, we will create a simple scene that changes the texture of an object when the scene starts. There are a few items that are neccessary to set up in advance. Only assets that exist in the Resources folder can be loaded at run time. Simply create a new folder at the top level of the Assets folder and name it "Resources", as shown here. In that example, the material "Blue" can be accessed while the assets in the "SampleProject" folder would be inaccessible.
Now, we need to add an object to our scene to place the material on. Create a blank scene and add a cube to the scene. Position it so that it is visible to the camera. It should look similar to this. I have elected to add a Red material to the cube to emphasize the transition, but this is not necessary.
The basic syntax for loading an asset from the resources folder is shown in line 11. That syntax is "Resources.Load<Type>(Asset_Path)". In the Type location, the type of asset is specified. In this example we are loading in a Material, but this can be changed to accommodate other types such as a Game Object in the case of loading a prefab. The "Asset_Path" is a string that holds the location of the asset relative to the Resources folder. I have elected to create a string variable in line 6 which holds the location of the asset as a matter of good practice, but this can be hard coded.
Now, simply drag and drop the LoadResources.cs script onto the cube object that was created earlier, and press play. When the simulation is run, the "Blue" material should be accessed and assigned to the cube.


No comments:
Post a Comment