I'm trying to make it so that the player closest to a block receives a tool once a certain block is in range of a model named Horse, after the model horse is deleted. The part of the script that recognizes that the block is in range of the Horse model is working properly, but I am now trying to get it so that the script will recognize the closest player to the brick so that it knows where to put the tool. here is the script.

local tool = game.Lighting.Tools.Horse

bin = script.Parent


function findNearestTorso(pos)
	local list = game.Workspace:GetChildren()
	local torso = nil
	local dist = 1000
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent.Parent.Parent.Parent) then
			temp = temp2:findFirstChild("Torso")
			human = temp2:findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
					script.Parent.Parent.Name = "Closest Person: " ..temp2.Name.. " l Distance: " ..(temp.Position - pos).magnitude.. " studs."
				end
			end
		end
	end
	return torso
end
while true do
wait()
findNearestTorso(bin.Position)
end

local function in_Range(part1,part2,range)

    if (part1.Position - part2.Position).magnitude <= range then
	
        return true

        -- alternatively

        -- return part2

    end

    return false

    -- alternatively

    -- return nil

end

 

debounce = false

 

while wait(0.5) do

 

    if in_Range(game.Workspace.gate,game.Workspace.Horse.Torso,30) == true then

        if debounce == false then debounce = true

            game.Workspace.Horse:Destroy()
            tool:Clone() .Parent = torso --This is the root of the entire problem, i'm trying to find a way to get the script to recognize where to put the tool (I want it in the closest player)
            wait(3)


        debounce = false end

    end

 

end

Any help is appreciated! Thanks guys! :)