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

Attempt to perform arritmetic(sub) on nil and Instance error?

local distance = 4
local uis = game:GetService("UserInputService")
uis.InputBegan:Connect(function(Input)
	if Input.KeyCode == Enum.KeyCode.E then
		local chr = game.Players.LocalPlayer.Character
		local mouse = game.Players.LocalPlayer:GetMouse()
		local torso = chr:FindFirstChild("Torso")
		if (torso-mouse.Target).magnitude < distance then
			mouse.Target.RemoteEvent:FireServer()
		end 
	end
end)

I get an error called attempt to perform arritmetic(sub) on nil and Instance. Local in startergui. Please help. Also I'm trying to make a script that sends a signal to the scripts inside the parts that the mouse is hovering over, resulting in interaction with objects. Hope you understand.

1 answer

✓ Accepted answer

On line 8 you tried to subtract wrong values. The minuend is the torso,which is an Instance and your subtrahend is Mouse.Target which is also an instance, instead use Mouse.Hit which returns the position in the workspace that the mouse is.

Fixed script:

local distance = 4
	local uis = game:GetService("UserInputService")
	uis.InputBegan:Connect(function(Input)
	    if Input.KeyCode == Enum.KeyCode.E then
	        local chr = game.Players.LocalPlayer.Character
	        local mouse = game.Players.LocalPlayer:GetMouse()
	        local torso = chr:FindFirstChild("Torso")
	        if (torso.Position-mouse.Hit.Position).magnitude < distance then
	            mouse.Target.RemoteEvent:FireServer()
	        end
	    end
	end)

Hope it helps!

1 comment

0

Oh so that s why.Thank you very much.

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