Attempt to index nil with character

local Players = game:GetService("Players")
local GetPlayers = Players:GetPlayers()

local Camera = game.Workspace.CurrentCamera
local Position = 1

local Spectate = script.Parent:FindFirstChild("Spectate")
local SpectateButton = script.Parent:FindFirstChild("SpectateButton")
local SpectateText = Spectate:FindFirstChild("TextLabel")
local NextButton = Spectate:FindFirstChild("TextButton")

SpectateButton.Activated:Connect(function()
	if Spectate.Visible == false then
		Spectate.Visible = true
	else
		Spectate.Visible = false
		Camera.CameraSubject = Players.LocalPlayer
	end
end)

NextButton.Activated:Connect(function()
	if GetPlayers[Position] ~= nil then
	    Position = Position + 1
		Camera.CameraSubject = GetPlayers[Position].Character.Humanoid
		SpectateText.Text = "Spectating "..Players[Position].Name
	else
		Camera.CameraSubject = GetPlayers[Position].Character.Humanoid
		SpectateText.Text = "Spectating "..Players[Position].Name
	end
end)

There’s more than one error here I believe

Players[Position], players is a service not a table

this may not work, but try putting a repeat wait() until game:IsLoaded() function at the top of the script (the script can’t get the players since the game hasn’t finished loading)

1 Like

You should getplayers everytime you update it

How could I implement that as I can’t get the position otherwise?

this no players have loaded yet so the table of getplayers is empty, {}

Everytime you try to get the current players just say players:GetPlayers()

Also is it a server script or localscript (i saw the localplayer but just to know)

This script is a local script.

Is this GetPlayers table empty? If yes, then you can use repeat wait() or put a wait() in it… you can also use the GetPlayers[Position]'s name and find the Character using CharacterFolder[PlayerName]

Alright I changed the function to this, but now its attempting to index nil with humanoid.

NextButton.Activated:Connect(function()
	if Players:GetPlayers(Position) ~= nil then
		Position = Position + 1
		Camera.CameraSubject = Players:GetPlayers(Position).Character.Humanoid
		SpectateText.Text = "Spectating "..Players:GetPlayers(Position).Name
	else
		Camera.CameraSubject = Players:GetPlayers(Position).Character.Humanoid
		SpectateText.Text = "Spectating "..Players:GetPlayers(Position).Name
	end
end)

The GetPlayers() instance method doesn’t receive any parameters so passing values as arguments to it won’t change anything.

local Player = Players:GetPlayers()[Position]
if Player then
	local Character = Player.Character
	if Character then
		local Humanoid = Character:FindFirstChildOfClass("Humanoid")
		if Humanoid then
			Camera.CameraSubject = Humanoid
		end
	end
end

You should make sure the variable named “Position” is not greater than the total number of players in the server.

3 Likes