Trouble making a random music play when a player takes damage

I’m new to scripting and I’m getting used to the fact that not all tutorials on youtube are helpful. I tried making a random music play when a player takes damage and stops automatically when a player no longer takes any damage, but everytime I try to make something similar to what I just said, it doesn’t work. It’s been weeks and none of the videos I’ve watched were helpful.

Any kind of help would be appreciated.

1 Like

So you want a music to play upon a player taking damage, and when after a while has passed with no damage being taken, the music should stop. Which means if the player constantly takes damage, the music should play on loop, until the player stops taking damage or dies. Is this correct?

Yes, this is exactly what I’ve been trying to make.

try this:

local music = -- reference sound object here

local humanoid = -- link player's humanoid here

local timeUntilMusicStops = 30 -- seconds
local hasDied = false
local lastDamage = 0
humanoid.HealthChanged:Connect(function()
	if not music.IsPlaying then
		music:Play()
	end
	lastDamage = tick()
	repeat
		task.wait(1)
	until tick() - lastDamage > timeUntilMusicStops or hasDied
	music:Stop()
end)
humanoid.Died:Connect(function()
	music:Stop()
	hasDied = true
end)
5 Likes

Is it possible to add multiple musics? Like instead of using only one music, theres a function where it picks a random music id.

yes, at the part where it does :Play(), you can set a new SoundId right above it.

You can have many sound id’s in a table and you can use math.random on the table to get a random id.

I really appreciate your help. Thank you

local soundIds = {
 0, 1, 2, 3, ...
}

then:

	if not music.IsPlaying then
		music.SoundId = "rbxassetid://"..soundIds[math.random(1,#soundIds)]
		music:Play()
	end

You’re welcome :slight_smile:

1 Like