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

Why isn't this loop working?

I have a while true do loop that checks if something in a player's backpack exists through a LocalScript. Here's the script:

repeat wait() until game.Players.LocalPlayer.Character
local gun = game.Players.LocalPlayer.Backpack:findFirstChild("Sniper Rifle")

while true do
	wait(1)
	if not gun then
		print("gun is nil")
	else
 		print("gun is not nil")
	end
end

The problem is, though, that even if the tool is removed, the output still says "gun is not nil", despite the gun not being in the player's inventory. Why is this happening?

1 answer

✓ Accepted answer

The problem here is that you're defining the gun outside the scope of the while loop. Doing this will make it check if the gun existed when it was defined, AKA when it wasn't nil to begin with.

So you have to define the gun inside the scope of the While loop for this to work.

wait(2)

local plr = game.Player.LocalPlayer
repeat wait() until plr.Character

while wait(1)
	local gun = plr.Backpack:findFirstChild("Sniper Rifle")
	if gun then
		print("gun is not nil")
	else
		print("gun is nil")
	end
end

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