Make HealthChanged update once every time it meets a conditional

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want HealthChanged to update once every time it meets a conditional.

  2. What is the issue? Include screenshots / videos if possible!
    I know HealthChanged event updates every time the player’s health changes but I want it to update once every time it meets a conditional to prevent lag and weird audio.

Streamable

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    Roblox Documentations and maybe a bit of Roblox’s Assistant but the AI didn’t understand or maybe I didn’t understand anything

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

local TweenService = game:GetService("TweenService")
local Players = game:GetService("Players")

local player = Players.LocalPlayer

local heartBeats = {
	"rbxassetid://176554627", -- Slow
	"rbxassetid://5948090748" -- Fast
}

-- Effects on player's screen
local InjureGUI = player.PlayerGui:WaitForChild("InjureGUI")
local blood = InjureGUI:WaitForChild("BloodVignette")
local heartbeat = InjureGUI.heartBeat

local function Injury(character)
	local humanoid = character:WaitForChild("Humanoid")
	
	blood.ImageTransparency = 1
	heartbeat.SoundId = ""
	heartbeat:Stop()
	print("Healthy")
	
	local function healthChange()
		local maxHealth = humanoid.MaxHealth
		print("Max health: ".. maxHealth)
		
		if humanoid.Health >= maxHealth / 1.25 then
			blood.ImageTransparency = 1
			heartbeat.SoundId = ""
			heartbeat:Stop()
			print("Healthy")
		elseif humanoid.Health < maxHealth / 1.25 and humanoid.Health >= maxHealth / 3 then
			blood.ImageTransparency = 0.6
			heartbeat.SoundId = heartBeats[1]
			heartbeat.Volume = 0.5
			heartbeat:Play()
			print("Injured")
		elseif humanoid.Health < maxHealth / 3 then
			blood.ImageTransparency = 0.3
			heartbeat.SoundId = heartBeats[2]
			heartbeat.Volume = 1.25
			heartbeat:Play()
			print("Seriously injured")
		end
	end
	
	humanoid.HealthChanged:Connect(healthChange)
end

-- Event connections
player.CharacterAdded:Connect(Injury)

if player.Character then
	Injury(player.Character)
end

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

1 Like

This shouldn’t really lag though I do get where you’re coming from for the audio. If you need to you can always store what sound is currently playing in a variable and check if its already the active one and just return so the sound doesn’t restart constantly.

1 Like

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