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

Arithmetic error when trying to change humanoid health?

Asked by 7 years ago

The goal of this script is when ever a player clicks on a different player, that player will be injured, but when ever i click i get this error attempt to perform arithmetic on field 'Health' (a nil value)

This is a local script

player = game.Players.LocalPlayer
character = game.Players.LocalPlayer.Character
gun = character:findFirstChild("Rifle")
mouse = player:GetMouse()

mouse.Button1Down:connect(function()
function getModel(raw)
for _,__ in next (workspace:GetChildren()) do
if raw:IsDescendantOf(__) then
return __;
end;
end;
return raw;
end;

local success,hum = pcall(function() return getModel(mouse.Target).Humanoid end);
hum.Health = hum.Health -15

end)

1 answer

Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
7 years ago

Your code is awkwardly "obfuscated" for lack of a better term, so let's fix that:

player = game.Players.LocalPlayer
character = player.Character
gun = character:FindFirstChild("Rifle")
mouse = player:GetMouse()

function getModel(raw)
    for _, child in pairs(workspace:GetChildren()) do
    --calling pairs is barely any slower than using next directly, plus it's easier to read.
        if raw:IsDescendantOf(child) then
            return child;
        end;
    end;
    return nil; --this allows us to not use pcall
end;

mouse.Button1Down:connect(function()
    if mouse.Target then
        local model = getModel(mouse.Target)
        if model and model:FindFirstChild("Humanoid") then
            model.Humanoid.Health = model.Humanoid.Health - 15
        end
    end
end)

Let me know if that still errors, or doesn't work in some way.

0
Overly complicated? pluginfactory 463 — 7y
0
Thank you pluginfactory 463 — 7y
Ad

Answer this question