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

Finding nearest player doesn't return anything after check?

I'm trying to find the nearest player or NPC within 50 studs and it finds all players but for some reason when I add code that checks if the player found isn't the local player it returns nothing.

local player = game.Players.LocalPlayer

for i,v in pairs(workspace:GetChildren()) do
	if v:FindFirstChild("Humanoid") then
		if player:DistanceFromCharacter(v.Head.Position) < 50 then
			if not player.Name == v.Name then
				print("Close player found that isn't local player!")					
			end
		end		
	end
end

2 answers

✓ Accepted answer

Try that

(~=) signified is not equal to ...

if player.Name ~= v.Name then
       print("Close player found that isn't local player!")
end                

So in ur script:

local player = game.Players.LocalPlayer

for i,v in pairs(workspace:GetChildren()) do
    if v:FindFirstChild("Humanoid") then
        if player:DistanceFromCharacter(v.Head.Position) < 50 then
            if player.Name ~= v.Name then
                print("Close player found that isn't local player!")                    
            end
        end     
    end
end

First put a RemoteEvent inside ReplicatedStorage then add a Script inside ServerScriptService and put this:

local rep = game:GetService('ReplicatedStorage')
local event = rep:FindFirstChild('RemoteEvent')
event.OnServerEvent:connect(function (plr, root)
	for _, i in pairs(game.Players:GetPlayers()) do
		if i.Character:FindFirstChild('HumanoidRootPart') then
			local userroot = i.Character.HumanoidRootPart
			local dist = (root.Position - userroot.Position).Magnitude
			if dist < 50 then
				event:FireClient(plr, i)
			end
		end
	end
end)

Then place this in your StarterGui Inside a LocalScript

wait()
local plr = game.Players.LocalPlayer
local char = plr.Character
local root = char:WaitForChild('HumanoidRootPart')
local rep = game:GetService('ReplicatedStorage')
local event = rep:FindFirstChild('RemoteEvent')

event:FireServer(root)

event.OnClientEvent:connect(function (closeby)
	print(closeby.Name.." Is Closeby")
end)

Make Sure you add the FireServer(root) on Line 08 whenever you want to find the distance of somebody.

3 comments

0

Just tested, It will work.

0

You are overcomplicating stuff, check the accepted answer.

0

This would run throughout other scripts, this would help out a whole lot later on when you have so many other scripts for something you only needed 2 for

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