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
01 | player = game.Players.LocalPlayer |
02 | character = game.Players.LocalPlayer.Character |
03 | gun = character:findFirstChild( "Rifle" ) |
04 | mouse = player:GetMouse() |
05 |
06 | mouse.Button 1 Down:connect( function () |
07 | function getModel(raw) |
08 | for _,__ in next (workspace:GetChildren()) do |
09 | if raw:IsDescendantOf(__) then |
10 | return __; |
11 | end ; |
12 | end ; |
13 | return raw; |
14 | end ; |
15 |
16 | local success,hum = pcall ( function () return getModel(mouse.Target).Humanoid end ); |
17 | hum.Health = hum.Health - 15 |
18 |
19 | end ) |
Your code is awkwardly "obfuscated" for lack of a better term, so let's fix that:
01 | player = game.Players.LocalPlayer |
02 | character = player.Character |
03 | gun = character:FindFirstChild( "Rifle" ) |
04 | mouse = player:GetMouse() |
05 |
06 | function 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 |
14 | end ; |
15 |
Let me know if that still errors, or doesn't work in some way.