Stop Errors From Appearing

Hello so basically I have a script to detect if the player is in range of a tool. Then it will show a GUI.

here’s the script:


UIS.InputChanged:Connect(function()
	if mouse.Target then
		local DistFromItem = player:DistanceFromCharacter(mouse.Target.Parent.Position)
		local MaxDistPickUp = 5
		
		if mouse.Target.Parent.Parent:IsA("Tool") and mouse.Target.Parent.Parent.Parent == game.Workspace.DroppedWeapons and DistFromItem < MaxDistPickUp then
			ToolPickupGUI.Enabled = true
			ToolPickupGUI.Adornee = mouse.Target
		else
			ToolPickupGUI.Enabled = false
			ToolPickupGUI.Adornee = nil
		end
	end
end)

But errors appear when I do “player:DistanceFromCharacter(mouse.Target.Parent.Position)”

It says position is not a valid member of “____”

I know why it is but how do I stop these errors from appearing or make it so it checks if the instance has a position.

The script works perfectly as is intended (if you ignore the errors)

mouse.Target.Parent is probably the model of the character/hit or workspace,

None of them has a position property.

It might be because you are moving your mouse across the sky or another object, which has no parent.

An easy fix is to check if the mouse target has a parent:

Hello! I tried to check if the mouse has a target, parent, and then, position. But the checks generate errors.

UIS.InputChanged:Connect(function()
	if mouse.Target then
		if mouse.Target.Parent then
			if mouse.Target.Parent.Position then
				local DistFromItem = player:DistanceFromCharacter(mouse.Target.Parent.Position)
				local MaxDistPickUp = 5
				
				if mouse.Target.Parent.Parent:IsA("Tool") and mouse.Target.Parent.Parent.Parent == game.Workspace.DroppedWeapons and DistFromItem < MaxDistPickUp then
					ToolPickupGUI.Enabled = true
					ToolPickupGUI.Adornee = mouse.Target
				else
					ToolPickupGUI.Enabled = false
					ToolPickupGUI.Adornee = nil
				end
			end
		end
	end
end)

This is the new code I used.

For example here is one of the errors.
image

Since youre already checking if there is ascendant of class tool, try checking if the parent of a mouse target is BasePart first (basically mouse.Target.Parent:IsA("BasePart")), then using the function to calculate player distance from parent of a mouse target, because attempting to index properties that do not exist will throw an error. BasePart is the main instance, and stuff like Part, WedgePart etc. inherit from BasePart, which is why :IsA("Basepart") works.

Thank you so much my guy Big Up :slight_smile: