Trying to create a Safe zone

I’m trying to create script where you touch a part you get a forcefield and when you leave it it gets removed.

What happens is that there is an error at line 36 telling me that I’m attempting to index nil with ‘FindFirstChild’ and I don’t understand the issue.

I’ve tried to look at other people’s posts with the same error but I couldn’t resolve it.

Here’s my code:

game.Players.PlayerAdded:Connect(function(player)
	local checkValue = Instance.new("BoolValue", player)
	checkValue.Name = "InSafeZone"
	checkValue.Value = false
end)

script.Parent.Touched:Connect(function(hit)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	if humanoid then
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
		if player then
			local check = player:FindFirstChild("InSafeZone")
			if check then
				check.Value = true
			end
		end
	end
end)

script.Parent.TouchEnded:Connect(function(hit)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	if humanoid then
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
		if player then
			local check = player:FindFirstChild("InSafeZone")
			if check then
				check.Value = false
			end
		end
	end
end)

while true do
	local players = game.Players:GetChildren()
	for i,v in ipairs(players) do
		local shieldCheck = v.Character:FindFirstChild("ForceField") -- Where the error occurs
		if v.InSafeZone.Value == true then
			if not shieldCheck then
				local newShield = Instance.new("ForceField", v.Character)
			end
		else
			if shieldCheck then
				shieldCheck:Destroy()
			end
		end
	end
	wait()
end

Hopefully you can understand the issue.

1 Like

It’s erroring because the character may not have loaded by the time the loop tries to get it, since if it doesn’t exist, it’ll try to use FindFirstChild on nil

Also if you’re creating a safe zone, Touched and TouchEnded are inefficient for this as they fire multiple times, regions would be a better way to do what you require

I recommend ZonePlus v2 as it features what you need for safe zones or other things requiring the usage of entering and leaving a zone

1 Like

You can :Connect() to the bool instead of using a while loop.

game.Players.PlayerAdded:Connect(function(player)
	local checkValue = Instance.new("BoolValue", player)
	checkValue.Name = "InSafeZone"
	checkValue.Value = false
    
	checkValue:GetProperyChangedSignal("Value"):Connect(function()
		if checkValue.Value then
			-- insert forcefield
		else
			-- remove forcefield
		end
	end)
end)

No while loop needed anymore…