Hey everyone, I’m having trouble with a script I drafted up and according to Script Analysis in studio everything should be working. Its a relatively simple script that checks if the player character is below 1/4 health and if they are they take a large amount of damage and I’ve posted it below.
Summary
local used = false
script.Parent.Touched:connect(function(part)
if not used then
used = true
if part.Parent then
local human = part.Parent:FindFirstChild("Humanoid")
if human.Health <= (human.Maxhealth/4) then
human.Health = human.Health - 999
end
wait (3)
used = false
end
end
end)
Could someone point me in the right direction? I’m completely stumped.
Hi, I see some things that might cause the problem. You should use :Connect instead of lower case :connect. In one line, you’re searching for a humanoid. If it doesn’t find a humanoid, it will return null, so it will error when you try to change it’s health. You also misspelt Humanoid.MaxHealth.
The code now would look like this
local used = false
script.Parent.Touched:connect(function(part)
-- will return if used is true
if used then return end
used = true
local human = part.Parent:FindFirstChild("Humanoid")
-- will return if it doesn't find a humanoid
if not human then return end
if human.Health <= (human.MaxHealth / 4) then
human.Health = human.Health - 999
wait(3)
used = false
end)
Ok, I understand what happens and this is probably the problem, the script works correctly but if you modify the player’s humanoid health from the explorer it will not work, this happens because when modifying it from the explorer the changes are only visible from the client.
Try looking for another way to set your humanoid health to 25.
Also humanoid.Maxhealth/4 is key sensitive so you should do it like this
I believe you can get the player from the character (thus proving that the parent of the touched part is a player character) and then find the humanoid as its descendent.
local character = game.Players:GetPlayerFromCharacter(part.Parent)
if not character then return end
local human = character:WaitForChild("Humanoid")
if not human then return end
-- do rest of stuff below