How to randomize played sounds?

I’ve been trying to edit the simple “Sad violin death sound” addon to play a random sound from a folder, when a player dies.

The problem I’m having is that it only plays one randomly picked sound from the folder, but I have to rerun the script using lua_openscript to make it play another sound.

I want it to play a different sound everytime when dying.


local die = {"death/death1.wav",
"death/death2.wav",
"death/death3.wav"
}


resource.AddFile("sound/death/death1.wav")
resource.AddFile("sound/death/death2.wav")
resource.AddFile("sound/death/death3.wav")


local noise = (die[math.random(1, #die)])
hook.Add("PlayerDeathSound", "DeFlatline", function() return true end)
hook.Add("PlayerDeath", "NewSound", function(vic,unused1,unused2) vic:EmitSound(noise) end)

I’m on my phone but I’ll try my best to get my point accross.

To play a random sound you need only use math.random like this,


 "sounds/death/splat" ..math.random(1,3).. ".wav";

Again… on my phone so I am sorry if I fucked something up.

Thanks for the quick answer, but it didn’t fix the problem. The sound doesn’t change. I still have to “manually” switch the soundclip by reloading the script. :confused:

It’s a small mistake on your part. The line which generates the “noise” variable is outside of any function, so it is executed only once when the script runs. That’s why it always plays the same sound.

All you have to do is move it inside the PlayerDeath hook, so it is generated every time a player dies.
Like this:


local die = {"death/death1.wav",
"death/death2.wav",
"death/death3.wav"
}


resource.AddFile("sound/death/death1.wav")
resource.AddFile("sound/death/death2.wav")
resource.AddFile("sound/death/death3.wav")



hook.Add("PlayerDeathSound", "DeFlatline", function() return true end)
hook.Add("PlayerDeath", "NewSound", function(vic,unused1,unused2)
	local noise = (die[math.random(1, #die)])
	vic:EmitSound(noise)
end)

Thank you! It works perfectly.