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

Function not returning properly?

function funcNear()
local nearestPlr 
	for _, val in pairs(game.Players:GetPlayers()) do
		local char = val.Character
		if char then 
			local dist = val:DistanceFromCharacter(script.Parent.HumanoidRootPart.Position)
			if dist < script.Parent.Configuration.TriggerDistance.Value then
				local nearestPlr = char
				print(nearestPlr)
			end
		end
	end
	return nearestPlr
end

while wait(3) do
	local x = funcNear()

	print(x)
end

nearestPlr is just returning nil when being called.

3 comments

1

You have to identify what nearestPlr is.

0

If no character is closer than script.Parent.Configuration.TriggerDistance.Value, then nearestPlr will never be assigned to. Also, if multiple characters are close enough, it will pick the first one it finds, rather than the one which is actually closer.

0

yeah im aware, this was mainly to test returning a value to another modulescript

1 answer

✓ Accepted answer

have you realized you created nearestPlr twice?

once in line 2, local nearestPlr

twice in line 8, local nearestPlr = char

that is two different variables!!!!

by the time it reach line 13, the second variable is out of scope, it is returning the value in first variable created in line 2. oops. you have never set that variable in the first place.

just remove "local " in line 8

1 comment

1

Thats what I told him. I guess, I have to be more specific next time.

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