Code review my player in range checking script?

`

local Players = game:GetService("Players")

local isPlayerNear = {}

function isPlayerNear(part : BasePart) --assuming all parts passed through are spheres
	local playerList = Players:GetPlayers()
	local nearbyPlayersList = {}
	if playerList == nil then return nearbyPlayersList end
	for i, plr in pairs(playerList) do
		local char = plr.Character or plr.CharacterAdded:Wait()
		local hrp = char:WaitForChild('HumanoidRootPart')
		local hrpPos = hrp.Position
		local partPos = part.Position
		
		local difference = hrpPos - partPos
		local radius = part.Size.Y
		if difference.Magnitude <= radius then
			table.insert(nearbyPlayersList, plr )
		end
		
	end
	return nearbyPlayersList
end

return isPlayerNear

if anyone can let me know how to improve this and also on how to make it so that it range checks in x,y and z directions, so i can use blocks, or other shapes instead of only spheres.
the point is to detect collissions (in a way), but i havent tried raycasts tho

1 Like

Hey,

I’ve went through your code and made some little micro-adjustments that could make it more readable and a wee bit fast, I’ve also left out some comments as to why I made such changes.

One change that I do not make however is the directional range check, I don’t really get what you mean by that, also the shape of the part doesn’t seem necessary here.

Here’s the improved code :wink:

--!strict

local Players = game:GetService("Players")

function isPlayerNear(part: BasePart): {Player}
	local nearbyPlayersList = {} :: {Player}
	
	-- defining the radius here, instead of doing it inside the loop.
	local partRadius = part.Size.Y
	
	-- previously a check was made on :GetPlayers() so that it attempt to do a loop if it was empty,
	-- but regardless if there are no players it will just return an empty table and thus no loop will be made
	-- and an empty nearbyPlayersList table would be returned.
	
	for _, player: Player in ipairs(Players:GetPlayers()) do
		-- there is absolutly no need to yield the loop using .CharacterAdded:Wait() or :WaitForChild(),
		-- instead just ignore the player and continue.
		
		local character = player.Character
		if not character then
			continue
		end
		
		local HumanoidRootPart = character:FindFirstChild("HumanoidRootPart") :: BasePart
		if not HumanoidRootPart then
			continue
		end
		
		-- and lastly, 'hrpPos' and 'partPos' are not needed, just put it all in single operation.
		local difference = (HumanoidRootPart.Position - part.Position).Magnitude
		if difference <= partRadius then
			table.insert(nearbyPlayersList, player)
		end
	end
	
	return nearbyPlayersList
end

return isPlayerNear

these will only work for parts that are a sphere essentially.
also yea i see the micro-adjustments as its just type checking mostly