- Home /
Multiple Sounds Clips when key pressed
If you can direct me to a previous post that would be great. I cannot find an answer for my question. So I will ask.
I am wondering how to make multiple audio clips play when you press a key. But only when near an object can they play. Example: you walk up to a cube, press enter it plays a sounds. Press enter again, it plays another one. I am also hoping to let the audio fully play out before the second audio can be played. I have asked a similar question before but it is for mouse click and to only play one clip. Check that out maybe!
Any idea will help!
Answer by Supercrusher9000 · Jan 30, 2014 at 03:48 AM
My guess would be to create an int variable simply by doing var [variable name] = 0. Then in the function, after it plays the sound just type Debug.Log([variable name]++); This will make it so when ever you press enter near the cube it switches to the next object. So simply have an if statement that says if([variable name] == 1){(then play that clip. So say you have 3 clips to play do that for all three and then have an if statement that states if([variable name > 3])(set [variable name to 0]) Sorry if this is hard to follow if you are still new, I don't have time to write out all the code. So let me know if your confused on anything.
Answer by Ashish Dwivedi · Jan 30, 2014 at 04:01 AM
Try with this class. Simply call "PlayAudio(clip)" method by passing audio clip. I think this would help you.
using UnityEngine;
using System.Collections;
public class PlayAudio
{
public delegate void AudioCallback();
public void PlaySound_newStyle( AudioClip clip)
{
if(isSoundoff)
return;
AudioSource audioSourceTemp = gameObject.AddComponent<AudioSource>();
audioSourceTemp.PlayOneShot(clip);
StartCoroutine(DelayedCallback(clip.length, ()=> Destroy(audioSourceTemp)));
}
private IEnumerator DelayedCallback(float time, AudioCallback callback)
{
yield return new WaitForSeconds(time);
callback();
}
}
Thanks for the replies! I will attempt this when I get home tonight. Any ideas how multiple audio would work? Basically I want it for a character, when you walk close to him and press enter, it will run through four different sounds clips each time you press enter. But only after the audio clip is finished playing, seems more natural for speaking audio :)
For multiple sounds:
public AudioClip[] clip;
.
.
.
AudioSource audioSourceTemp = gameObject.AddComponent<AudioSource>();
audioSourceTemp.PlayOneShot(clip[Random.Range(0, clip.Length)]);
Your answer
![](https://koobas.hobune.stream/wayback/20220613132054im_/https://answers.unity.com/themes/thub/images/avi.jpg)