Reputation: 545
How do I refer to specific files in the ProjectView that will not have been prefabbed or instantiated yet in the game? I know I can use Resources.Load, but I also always see people say not to use that method if at all possible.
Specifically, I am trying to create a method that creates an empty object with an AudioSource and plays whichever sound file I tell it to play. I don't want to have to create every Audioclip component in advance (plus I'd have a million prefabs by the end of it), but I need to tell it which sound file to play.
Also, does the .Load method work outside of Resources? I don't want to change my ProjectView hierarchy if I can avoid it, but Resources.Load only works on files that sit in the resources folder.
Upvotes: 0
Views: 41
Reputation: 2516
Try out the code below. What you need to do is supply the name of the clip you want to play. Of course, this clip does need to reside inside the "Resources" folder.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LoadingSample : MonoBehaviour {
public void LoadASoundClip (string clipName) {
//Instantiate a new empty GameObject
GameObject go = new GameObject();
//Add an Audio Source component, and get it
go.AddComponent<AudioSource>();
var audioSource = go.GetComponent<AudioSource>();
//Assign the clip for the audio source
audioSource.clip = Resources.Load<AudioClip>(clipName);
}
}
Also, why shouldn't you use Resources.Load at all? It's an intensive method, but used diligently it won't hurt the performance of your game much.
There are other means of loading and unloading files, such as FileStream, but these are more convoluted, and just add onto the work needed to be done. This however lets you store files outside the Resources folder.
One of the biggest advantages of Resources though, is that any file inside it is automatically added to the build, regardless of whether it's used in a scene or not. Your case is an excellent example of when this is useful. You may not have any of these audio clips in any scene, but you can load and unload them at runtime.
If you don't use the Resources folder, then you have to ensure that that files you don't have in a scene are manually added into the build.
Upvotes: 1