Playing sounds - choosing randomly between three

This is something I don’t have a clue about. If I have a weapon that makes a sound each time it instantiates fires, how could I make it choose between three similar, but different sounds?

I also want to make this kind of thing happen for vehicles, and explosions - when they explode, to choose one of three… Would this use a similar type of scripting?

Arrays and Random :slight_smile:

var things : Thing[];

function Blargh() {
 var chosenThing : int = Random.value * (X-1);
 things[ chosenThing ].DoSomething();
}

things can be assigned in the Inspector view.

Random.value returns a float between 0.0 and 1.0. If you convert that to int I think it will always return 0. And eitherway I don’t see your logic of returning 0 or 1 * (X-1). What is X? And you would return 0 or X-1 in either case, not really random.

I would do:

var sounds : AudioClip[];

function PlayRandomSound() {
    audio.clip = sounds[Random.Range(0, sounds.Length)];
    audio.Play();
}

If you have an array with 3 sounds those 3 sounds will be array[0], array[1], array[2]. If you use sounds.Length on that array it will return 3 and thus you would normally have to use sounds.Length - 1 to avoid trying to access array[3] which doesn’t exist, but Random.Range() never returns max when used with int so it will only return the numbers 0, 1, 2 which suits us perfectly.

I use C# so the syntax may be incorrect.

@TwiiK : I see you never programmed anything on the TI-82 (or, you always used languages providing such comfort, as Random.Range (start : int, end : int)) :slight_smile:

Sure, Random.value returns something between 0.0 and 1.0. By multiplying this value by X, you get a value between 0.0 * X and 1.0 * X (so, 0.0 and X, as simple as that). What is X, do you ask ? Simply a variable Vicenti forgot to declare / assign, but it is not the most difficult (the most efficient would be var X : int = things.length.

When comfort isn’t present, you have to manage. But since it is present (Random.Range), why bothering in using tricks like this ? :wink:

Yeah, that makes sense. Thanks for clearing that up. The javascript syntax makes thing less clear for me as well. :slight_smile:

Eitherway X shouldn’t really be X at all. Anything other than things.Length wouldn’t make sense in this case. Just saying. :slight_smile:

Ha, what, we have a functional Range function?
jawdrop
Unity is so <3.

X originally made sense but I safed-up the code a bit and it got left in there accidentally.

The Random.Range from Twiik is a better solution. :slight_smile:

I disagree ! One year of spaghetti code, and you produce a heavy monster programmer…:slight_smile:

I mean Random.Range[0,length] is more good reading, heh, than Random.value * (length-1), since it specifically states what it’s doing (random value from range), while Random.value is just a random value.