How to track the player with a range of distance if i want to add things to the player?

well by this I mean how can I find the player in game.Players if I’m using a range of distance, I already tried but it won’t let me and I don’t know the answer.

local function DistanceToEnabled(plr)
	local target = nil
	local Range= 15
	for i, Dis in pairs(workspace:GetChildren()) do
		local Human  = Dis:FindFirstChild("Humanoid")
		local Torso = Dis:FindFirstChild("UpperTorso")
		
		if Human and Torso and Dis ~= script.Parent then
			if (RangeTronco.Position - Torso.Position).magnitude < Range then
				Range = (RangeTronco.Position - Torso.Position).magnitude
				target = Torso.Position
				plr = Dis--According to me, this is to track the player
				local player = Players:FindFirstChild(plr)
				local Backpack = player:FindFirstChild("Backpack")--Here it gives me the error
end
end
end
end

this was what I tried but it only gave me the error of “Argument 1 missing or nil”, the name does find it but does not let me apply it when looking for the player in game.Players

You shouldn’t be looping through the workspace’s children because you will be looping through a whole lot more than just the players, and you need extra logic in determining the object is a player or not. Instead, use game.Players:GetPlayers() to get a list of the game’s players.

As for the error you’re getting, it actually stems from the line just about where the output is erroring;

In this line, plr refers to the player’s model, not the player’s instance. The Backpack isn’t parented to the model.

With all this, your script should look something like

local function DistanceToEnabled(plr)
    local Range = 15
    for i, player in pairs(game.Players:GetPlayers()) do
        local torso = player:FindFirstChild("HumanoidRootPart")
        if torso and (RangeTronco.Position - Torso.Position).Magnitude < Range then
            local Backpack = player:FindFirstChild("Backpack")
        end
    end
end
1 Like