- Home /
Playing multiple sounds on same key input ("e")
Hi people,
So, I haven't been on Unity Answers in a while as I like to learn things the hard way.. However, this one has just completely frustrated me and I just can't seem to wrap my head around it.
The way I want this to work is by the character going up to a cup to press the E key which should then play the first sound, WAIT FOR IT TO FINISH, then when they press the E key again, it should play the soundClip2 AudioClip and then WAIT FOR IT TO FINISH, and lastly, play the soundClip3 when the user presses E.
After that is all done, I want it to go back to the top of the script. Do I need to add a Function Update or anything?
It would be really appreciated if you could get me sorted on this problem as it's begun to put a halt on my project.
public var soundClip1 : AudioClip; public var soundClip2 : AudioClip; public var soundClip3 : AudioClip; // Play default sound function OnTriggerStay (col:Collider){ if(Input.GetKey("e")) { audio.clip = soundClip1; audio.Play(); yield WaitForSeconds (soundClip1.audio.clip.length); } else if(Input.GetKey("e")) { audio.clip = soundClip2; audio.Play(); yield WaitForSeconds (soundClip2.audio.clip.length); } else if(Input.GetKey("e")) { audio.clip = soundClip3; audio.Play(); yield WaitForSeconds (soundClip3.audio.clip.length); } }
Here is the scene I am working on
Because I can't get this script to work, I have decided to stick to a shortenered version of it, but that's not what I want as it only plays one sound. ALSO when I keep pressing E, it spams the sound.. I want it to play the sound once, and then when it finishes, it plays again when the E key is pressed. I have tried PlayOneShot, and it tells me something like Unity can't support it or so..
public var soundClip1 : AudioClip;
public var soundClip2 : AudioClip;
public var soundClip3 : AudioClip;
// Play default sound
function OnTriggerStay (col:Collider){
if(Input.GetKey("e")) {
audio.clip = soundClip1;
audio.Play();
yield WaitForSeconds (soundClip1.audio.clip.length);
}
}
**If you manage to understand the problem I am facing, I won't know how much to thank you! Please please please! Help me out! The Unity Community is very good and that is why I have chosen to write my issues here.
Thanks.**
Answer by Nerevar · Jun 25, 2014 at 01:06 PM
Hello,
Assuming the OnTriggerStay() is actually triggered, I think you can simply do like this:
public var soundClip : AudioClip[]; //to be assigned in inspector
private var looper : int = 0;
function OnTriggerStay (col:Collider){
if(Input.GetKey("e")) {
if(!audio.isPlaying)
{
audio.clip = soundClip[looper];
audio.Play();
looper++;
looper = looper%soundClip.Length;
}
}
}
regards
Hi Nerevar,
This is absouletly brilliant mate! This was exactly what I was looking for. Thank you so much! I've also learned from this.
Brilliant stuff!