Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Arithmetic error when trying to change humanoid health?

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

✓ Accepted answer

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.

2 comments

0

Overly complicated?

0

Thank you

This discussion is preserved as it was. New answers, comments, and votes are closed.