Attempt to call a nil value

  1. Change team of person closed to player

  2. Errors and says attempt to call a nil value

local player = game.Players.LocalPlayer
local players = game.Workspace:WaitForChild("Players")

local rs = game:GetService("ReplicatedStorage")
local folder = rs:WaitForChild("remotes")
local name = script.Parent.Parent.Username
local Character = game.Players.LocalPlayer.Character
local HumanoidRootPart = Character and Character:FindFirstChild("HumanoidRootPart")
if not (Character or HumanoidRootPart) then return end

local TargetDistance = math.huge
local Target

for i,v in ipairs(game.Players:GetPlayers()) do
	if v ~= game.Players.LocalPlayer and v.Character and v.Character:FindFirstChild("HumanoidRootPart") then
		local TargetHRP = v.Character.HumanoidRootPart
		local mag = (HumanoidRootPart.Position - TargetHRP.Position).magnitude
		if mag < TargetDistance then
			TargetDistance = mag
			Target = v

function Open()
				print(Target.Name)
				print("Fired")

folder.book:FireServer(player,Target)
				end
		end
	end
	end
	
script.Parent.MouseButton1Down:Connect(Open)





It doesn’t say in the error message

Can you copy and paste the full error then? The whole line in the output?

image

Probably this happens because when the loop runs, there’s only one player, which is the LocalPlayer, so it will not create the function and when trying to connect it, it will not exist (be nil).

I’m assuming you want to detect if there’s any player near every second or every time, so instead loop every RenderStep and take out the global function from the loop.

local players = game.Workspace:WaitForChild("Players")

local RunService = game:GetService("RunService")
local PlayersService = game:GetService("Players")
local rs = game:GetService("ReplicatedStorage")

local player = PlayersService.LocalPlayer

local folder = rs:WaitForChild("remotes")
local name = script.Parent.Parent.Username
local Character = game.Players.LocalPlayer.Character
local HumanoidRootPart = Character and Character:FindFirstChild("HumanoidRootPart")
if not (Character or HumanoidRootPart) then return end

local TargetDistance = math.huge
local Target

local function Open()
	print(Target.Name)
	print("Fired")

	folder.book:FireServer(player,Target)
end

RunService.RenderStepped:Connect(function()
	for _, v in ipairs(PlayersService:GetPlayers()) do
		if v ~= player and v.Character and v.Character:FindFirstChild("HumanoidRootPart") then
			local TargetHRP = v.Character.HumanoidRootPart
			local mag = (HumanoidRootPart.Position - TargetHRP.Position).Magnitude
			if mag < TargetDistance then
				TargetDistance = mag
				Target = v
			end
		end
	end
end)


script.Parent.MouseButton1Down:Connect(Open)

I only want to check it once the Open function is called.