I am trying to make a system where it finds the closest part to a player. The issue is that I get an error saying “attempt to compare number and nil” even though it prints the number out not nil. I have looked stuff up on the dev fourm and found none of it works for me. I have attached the code below.
for i,plr in ipairs(Players)do
local char = plr.Character
local mag = tonumber((char.HumanoidRootPart.Position - HRP.Position).Magnitude)
if plr.Name~=Target.Name then
if Target.Value == nil then
ClosestMag = mag
Target.Value = plr
print(type(ClosestMag))
elseif ClosestMag>mag then
ClosestMag = mag
Target.Value = plr
end
end
end
Magnitude already returns a number, so you just need to do
local mag = (char.HumanoidRootPart.Position - HRP.Position).Magnitude
Also it could be that ClosestMag is nil? Maybe try this?
for i,plr in ipairs(Players)do
local char = plr.Character
local mag = (char.HumanoidRootPart.Position - HRP.Position).Magnitude
if plr.Name~=Target.Name then
if Target.Value == nil or (ClosestMag and ClosestMag > mag) then
ClosestMag = mag
Target.Value = plr
print(type(ClosestMag))
end
end
end
I combine the 2 statements since they effectively did the same thing.
It’s likely that your ClosestMag thing is not created properly? How are you making it?
When I combined the two statements it through an error. I already knew making it a magnitude would produce a number but it was saying it was nil so I tried something else. The “ClosestMag” variable was created before the ‘for loop’ and the value is changed to “mag” if “mag” is found to be smaller than the current ClosestMag’s magnitude. I am storing the “Target” value in a ‘ObjectValue’ nested in the script allowing for more flexibility. I have had trouble using values before in place of variables.
Could you printing the thing in mag and the thing in ClosestMag? I still think it’s an issue with ClosestMag, but debugging should show us what’s going on