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.
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?
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)