Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago
Edited 7 years ago

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

Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

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)
Ad

Answer this question