How can I make a script that plays a selection of sounds at random?

What are you attempting to achieve?
I want to make certain sounds play at random or when a vehicle (in this case, a train) isn’t moving. Such sounds would be:

When stationary:

  • air releasing or air compressor sounds
  • ticking or spitting (similar to the sounds a car makes after you turn it off after driving and it just sits)
  • audible passenger or freight effects like people talking, radio chatter, and other ambient

When moving:

  • train car squeals, squeaks, or ‘flat spots’ (the thumping you hear on some train cars as they go by)

What is the issue?
I don’t know how to make an efficient script that does this. My game is built by several of us and we do have a lead scripter, but he’s currently working on something in it that has far more priority and I wish not to interrupt him.

What solutions have you tried so far?
I thought about taking a script from a friend of mine that has a sound pack that includes a sound-randomizing script and altering it, but I decided against this as the method I had in mind seems inefficient, impractical, and memory consuming.



You can pick random sounds to play from a table of selected sounds by using the Random feature. For instance:

local sounds = {sound1, sound2, sound3, sound4, sound5}
local r =

function pickRandomSound()
    local randomIndex = r:NextInteger(1, #sounds)
    return sounds[randomIndex]

There are no performance issues with this.


Ok thank you, but what if I want to make the sound play at different intervals? By this, I mean maybe a sound plays, then many seconds later (from a range of 30 seconds to 2 minutes example) another sound plays?

Also, does that script cover the fact that I want to have certain sounds play when the train is stopped and certain sounds play when it’s moving?

You could just use seperate arrays for each “state” that you need. Ie. Randomly choosing from the one which corresponds to the motion of the train.

That is of course assuming that you already have some system in place which keeps track of this with an integer or something.