Random damage sound doesn't work as expected

  1. What do you want to achieve? So i made a script that it’s supposed to play random damage sounds when player gets damaged and waits until the damage sound ends to play the next one when getting damaged

  2. What is the issue? It keeps playing when i’m not getting damaged and doesn’t work after player resets

  3. What solutions have you tried so far? i didn’t found any solution

this is a local script in starterplayerscripts

local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer
local character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")

local sounds = {
	"rbxassetid://not going to show",
	"rbxassetid://not going to show",
	"rbxassetid://not going to show",
	"rbxassetid://not going to show",
	"rbxassetid://not going to show",
	"rbxassetid://not going to show",
	"rbxassetid://not going to show"
}

local soundFolder = Instance.new("Folder")
soundFolder.Name = "DamageSounds"
soundFolder.Parent = LocalPlayer:WaitForChild("PlayerGui")

local soundObjects = {}
for i, soundId in ipairs(sounds) do
	local sound = Instance.new("Sound")
	sound.SoundId = soundId
	sound.Volume = 1
	sound.Name = "Sound" .. i
	sound.Parent = soundFolder
	table.insert(soundObjects, sound)
end

local canPlaySound = true

local function playRandomSound()
	if canPlaySound then
		canPlaySound = false
		local randomIndex = math.random(1, #soundObjects)
		local selectedSound = soundObjects[randomIndex]
		selectedSound:Play()

		selectedSound.Ended:Wait()
		canPlaySound = true
	end
end

humanoid.HealthChanged:Connect(function(health)
	if health < humanoid.MaxHealth then
		playRandomSound()
	end
end)
3 Likes

i… dont think that’s how it works.

i think it shoulda’ be like this;

local currentHealthVal = humanoid.Health -- put this outside the function, or rather right after declaring the humanoid.
-- now, put this in the function
local ammountChanged = math.abs(currentHealthVal-health)
if currentHealthVal > health then
	playRandomSound()
end
currentHealthVal = health
2 Likes

that fixes it but it doesn’t work after reset, don’t worry i’ll try to fix it myself i think i know why it doesn’t work after reset (so yeah basically the damagesounds folder destroys after player resets)

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.