- Home /
Multiple audio sources on a game object, how to script to play sequentially?
User selects object with ray. Want object to give different sounds when selecting in timeframe.
Click once get noise1 Click twice (within 10sec) get noise2 Click three times (within 10 more sec) get noise3
otherwise get noise1
Any ideas on how to do this?
Current Script:
public AudioSource[] sounds;
public AudioSource noise1;
public AudioSource noise2;
public AudioSource noise3;
void Start()
sounds = GetComponents<AudioSource>();
noise1 = sounds[0];
noise2 = sounds[1];
noise3 = sounds[2];
\\ And then to play:
public override void Activate()
{
if (timer > 0f)
return;
noise1.Play();
noise2.Play();
noise3.Play();
Answer by imp903 · Jun 17, 2015 at 02:21 AM
I'm not great with C# but I can describe how I would do it anyway and hopefully you can figure out how you would do that in C#, sorry I can't give anything beyond this. I would create a variable called timer like you did, and default it to zero. then every time the button was clicked I would set timer back equal to ten, but in the update function, I would make sure the timer counted down as long as the variable timer was greater than 0. I would then create a variable called timesClicked which would default to zero, but would add one to itself every time the button was clicked. At the end of my update function I would include that when timer
for the hell of it, here's a js script and maybe that helps anyway:
var timer = 0;
var timesClicked = 0;
var AudioSource = GetComponent.<AudioSource>();
var noise1 : AudioClip;
var noise2 : AudioClip;
var noise3 : AudioClip;
function OnClick()
{
timer = 10;
if (timesClicked ==0)
{
AudioSource.clip = noise1;
AudioSource.Play();
timesClicked ++;
}
if (timesClicked == 1)
{
AudioSource.clip = noise2;
AudioSource.Play();
timesClicked++;
}
if (timesClicked == 2)
{
AudioSource.clip = noise3;
AudioSource.Play();
timesClicked = 0;
}
}
function Update()
{
if (timer>0)
{
//this line is flawed because Time.time accounts for frames so 10 is a fraction of a second here
//some experimenting will find a proper timer value at the top
timer -= Time.time;
}
if (timer <=0)
{
timesClicked = 0;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613201050im_/https://answers.unity.com/themes/thub/images/avi.jpg)