What do you want to achieve? I want to play a looped heartbeat sound when the humanoid’s health is equal inferior to 10.
What is the issue? I made a local script in StarterCharacterScripts that utilizes an if else statement. It checks if the humanoid’s health is equal or below 10 then plays the sound. Then, if the humanoid’s health is not equal or below 10 it uses an if statement that checks if it is playing, and, if true, it stops the loop and the sound. I then tested this and when the humanoid’s health was below or equal to 10, it did not work.
What solutions have you tried so far? I tried moving it to StarterGui and StarterPlayerScripts. I also tried to find the solution in the dev forum by viewing different posts about client-sided sounds.
The problem with your script here is that it only runs once. This is bad as when the character first spawns, this script will run, but it spawns with 100 health so the loop will evaluate as false. Very simple fix; we use an event called “GetPropertyChangedSignal”, which you can find the documentation here: documentation.
So how does this event work? Well, it fires every time the given property is changed. e.g.; a simple script that prints whenever the players health gets changed
local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local heartbeatSound = workspace:WaitForChild("sounds").heartBeatSound
humanoid:GetPropertyChangedSignal("Health"):Connect(function()
print(player.DisplayName .. " health changed to " .. humanoid.Health)
end)
Here is proof of it working (number increases because of health regen)
and with a little modification of this script, we can change it to do what you want it to do;
local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local heartbeatSound = workspace:WaitForChild("sounds").heartBeatSound
humanoid:GetPropertyChangedSignal("Health"):Connect(function()
if humanoid.Health <= 10 then
if heartbeatSound.Playing == false then
heartbeatSound:Play()
end
else
if heartbeatSound.Playing == true then
heartbeatSound:Stop()
end
end
end)
All done, keep in mind the audio should be looped, so you hear it more than once.
Keep in mind this script should be a local script in StarterCharacterScripts