Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

I keep getting "attempt to index field '?' (a nil value)" how do I fix this?

I have a simple script that checks if a player is afk or not, however when I run it I keep getting this warning: "attempt to index field '?' (a nil value)"

Here is the code where it is having problems and the error comes up on line four. The script is currently located in game.ServerScriptService

players = game.Players:GetChildren()

for i = 1, #players do
	if players[i]:FindFirstChild("IsPlaying") then
		if players[i].IsPlaying.Value == false then
			table.remove(players, i)
		end
	end
end

I'm pretty new to this so any help is appreciated!

2 answers

✓ Accepted answer

A problem you're doing here is that you're using for 1,#players do, when doing this you are keeping i as 1 and running the same code without changing i meaning what you're always selecting the same player, try using for i,v in pairs loop. I also saved the IsPlaying value in a local variable and if it doesn't exist set it to false

players = game:GetService("Players"):GetChildren()

for i,v in pairs(players) do
local isPlaying = v:FindFirstChild("IsPlaying") or false
    if isPlaying ~= false then
        if isPlaying.Value == false then
            table.remove(players, i)
        end
    end
end

Now instead of doing players[i] you just do v! If this worked and helped you, then mark this as the answer!

1 comment

0

It works now! Thank you so much! :D

Old Code:

players = game.Players:GetChildren()

for i = 1, #players do
    if players[i]:FindFirstChild("IsPlaying") then
        if players[i].IsPlaying.Value == false then
            table.remove(players, i)
        end
    end
end

I can see you're trying to see if that you want it to remove the player from the table of players if theyre afk. your first if statement is not required at all and is wrote wrong. you dont need the findfirstchild as You can assume it exists as this is most likely a server script and i am assuming you have working code to add the value. Corrected Code:

players = game.Players:GetChildren()

for i = 1, #players do
     if players[i].IsPlaying.Value == false then
         table.remove(players, i)
     end
end

1 comment

0

I disagree, you should always check if an object that was added by another script is existent before doing anything else with it. The last thing you want is one line of code to error and it to cause a chain reaction to other scripts.

This discussion is preserved as it was. New answers, comments, and votes are closed.