Is there a way to update the audioclip of an object pooled audiosource instance?
Hello,
I have an object pool of audiosource instances that I'd like to change the default audioclip of during runtime. I'm a complete noob to coding, sorry if the question is very basic :)
I've got this in the Start method. Is there maybe something I can add to the Update function to change the default audioclip of the instantiated objects?
void Start () {
pooledAudios = new List<AudioSource> ();
for (int i = 0; i < pooledAmount; i++) {
AudioSource audio = (AudioSource)Instantiate (pooledAudioSource);
audio.gameObject.SetActive (false);
pooledAudios.Add (audio);
}
}
HUGE thanks to anyone who can help! :)
Answer by EvyBenita · Jul 09, 2016 at 07:03 PM
Sorry, this is my full ObjectPooler script:
public class ObjectPooler : MonoBehaviour {
public AudioSource pooledAudioSource;
public int pooledAmount = 10;
public bool willGrow = true; //lets the audiosource list grow if it's needed.
List<AudioSource> pooledAudios;
void Start () {
pooledAudios = new List<AudioSource> ();
for (int i = 0; i < pooledAmount; i++) {
AudioSource audio = (AudioSource)Instantiate (pooledAudioSource);
audio.gameObject.SetActive (false);
pooledAudios.Add (audio);
}
}
void Update(){
}
public AudioSource GetPooledAudio(){
for(int i = 0; i < pooledAudios.Count; i++){
if(!pooledAudios[i].gameObject.activeInHierarchy){
return pooledAudios[i];
}
}
if (willGrow) {
AudioSource audio = (AudioSource)Instantiate (pooledAudioSource);
pooledAudios.Add (audio);
return audio;
}
return null;
}
}
And this my SoundSwap script, which works fine on non-list audio:
public AudioSource zone;
public AudioClip clip1;
void OnTriggerEnter2D(Collider2D other){
if (other.gameObject.tag == "player") {
// Debug.Log ("audio clip swapped"); zone.clip = clip1;
}
}
Got it working in the end. Ins$$anonymous$$d of changing the instances themselves, I'm changing the clip in the coroutines where I'm calling them, and a public static variable as an identifier of which clip to play. There's probably a better way of doing it, but at least it works :)
Your answer
Follow this Question
Related Questions
Newbie with OnTriggerEnter & Audio Files 0 Answers
I want the audio to play when the player nears the object, but fade away when they walk away. 0 Answers
Audio won't play on collision 0 Answers
Determine end of audio clip if paused and resumed inbetween? 1 Answer
Object Reference not set to an instance of an object 0 Answers