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 8 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

01player = game.Players.LocalPlayer
02character = game.Players.LocalPlayer.Character
03gun = character:findFirstChild("Rifle")
04mouse = player:GetMouse()
05 
06mouse.Button1Down:connect(function()
07function getModel(raw)
08for _,__ in next (workspace:GetChildren()) do
09if raw:IsDescendantOf(__) then
10return __;
11end;
12end;
13return raw;
14end;
15 
16local success,hum = pcall(function() return getModel(mouse.Target).Humanoid end);
17hum.Health = hum.Health -15
18 
19end)

1 answer

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

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

01player = game.Players.LocalPlayer
02character = player.Character
03gun = character:FindFirstChild("Rifle")
04mouse = player:GetMouse()
05 
06function getModel(raw)
07    for _, child in pairs(workspace:GetChildren()) do
08    --calling pairs is barely any slower than using next directly, plus it's easier to read.
09        if raw:IsDescendantOf(child) then
10            return child;
11        end;
12    end;
13    return nil; --this allows us to not use pcall
14end;
15 
View all 23 lines...

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

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

Answer this question