Loading resources with the ResourceResources.Load() function
If you instead prefer to load in the prefabs using script, the ResourceResources.Load() function will help you with that. I am not as familiar with it, but you can find documentation on it here.
ResourceResources.Load(string) looks in your resources folder for any prefab matching the string. You can look directly for a prefab with ResourceResources.Load("prefabName"), or look in a specific folder with ResourceResources.Load("folder/prefabName". Note that we always use forward slashes. This is important, as while you may be use interchanging the forward slash (/) with a backward slash (\) for use with alternate operating systems, Unity always accepts the forward slash (/), regardless of the operating system.
You can overload the function with a type, in order to narrow your selection down. ResourceResources.Load("prefabName", typeof(GameObject) will only return GameObjects, even if you have a texture that is also named "prefabName".
- If the search returns multiple prefabs, it will return an array of the prefabs. If your code is set up to only interpret a single instance, this can lead to errors. Unless you intend to load an array of like-named prefabs, I would recommend ensuring your prefabs each use different names. Regardless, this is generally a good idea for the purpose of keeping your project tidy. 50 tips for working with Unity (Best Practices) offers some sound advice for naming conventions, as well as a plethora of other useful tips.
- If the search returns no prefab, it will instead return
null. Obviously, this should not happen. It might still be a good idea to double check that your prefab reference!= nullafter yourResourceResources.Load(), to prevent possible issues, later.
GameObject prefab
// Loading in the reference to your prefab
prefab = ResourceResources.Load("prefabName", typeof(GameObject)) as GameObject;
// Loading in and instantiating an instance of your prefab
prefab = Instantiate(ResourceResources.Load("prefabName", typeof(GameObject))) as GameObject;