Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Changing a character's humanoid health if it goes over 120 or a specific value?

LocalScript in StarterGui

local maxHealth = 120 -- Used to define the max amount of health for players.
local player = game.Players.LocalPlayer --Can only be used in local scripts
local event = game.ReplicatedStorage:WaitForChild('HealthChanged') --Requires RemoteEvent in Replicated Storage called HealthChanged
player.CharacterAdded:connect(char) --When the character is added
    local humanoid = char:WaitForChild('Humanoid') --Wait for Humanoid
    humanoid.HealthChanged:connect(function() --When the humanoid's health changes
        if humanoid.Health > maxHealth then --Check for if it's higher than the maxHealth
            event:FireServer(humanoid) --Fire the server with the humanoid
        end
    end)
end)

Script in ServerScriptStorage


local maxHealth = 120 -- Used to define the max amount of health for players.
local event = game.ReplicatedStorage:WaitForChild('HealthChanged') --Grabs event
event.OnServerEvent:connect(function(player, humanoid) --When the event is triggered by client, grab the player and humanoid
    humanoid.Health = maxHealth --Change the health to maxHealth
end)

1 answer

Your problem here is with your networking, not necessarily the code. You can execute all of your code on the server - no need for remotes. Just simply place a script in ServerScriptStorage.

What you have to do is use a PlayerAdded event to access every potential player to enter the server.

You can then repeat your usage of the CharacterAdded event, and the HealthChanged event, compare, and configure if necessary.

local maxHealth = 120

game.Players.PlayerAdded:Connect(function(player) --Player joins
	player.CharacterAdded:Connect(char) --Player's character adds
		local humanoid = char:WaitForChild('Humanoid')
		humanoid.HealthChanged:Connect(function(h) --Health changes
			if h > maxHealth then --Change if it's higher than maxHealth
				humanoid.Health = maxHealth
				humanoid.MaxHealth = maxHealth
			end
		end)
	end)
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.