Error from a function

So, I was making my music zone script and I came across this error. It looks like the pair isn’t an object.


Here is my script.

local collectionservice = game:GetService("CollectionService")
local zones = workspace:WaitForChild("Zones")
local parts = collectionservice:GetTagged("Zone")
local tweenservice = game:GetService("TweenService")
local runservice = game:GetService("RunService")

local function inZone(zone)
	if not zone.Ambience.Playing then zone.Ambience.Ambience:Play() end
	tweenservice:Create(zone.Ambience.Ambience, TweenInfo.new(0.2), {Volume = 1}):Play()
end

local function leftZone(zone)
	tweenservice:Create(zone.Ambience.Ambience, TweenInfo.new(0.2), {Volume = 0}):Play()
end

runservice.RenderStepped:Connect(function()
	for i, zone in pairs(parts) do
		print(zone)
		local region = Region3.new(zone.Position - zone.Size/2, zone.Position + zone.Size/2)
		local regionparts = workspace:FindPartsInRegion3WithWhiteList(region, game.Players.LocalPlayer.Character:GetDescendants())
		for _, zone in pairs(regionparts) do
			if zone:FindFirstAncestor(game.Players.LocalPlayer.Name) then
				inZone()
				break
			else
				leftZone()
			end
		end
	end
end)

Any help is appreciated.

You’re calling the inZone() function with no arguments, so of course inside the function zone is nil. Also, you have a for loop inside another for loop that are both trying to use ‘zone’ as a loop variable. Best not to shadow variables like this, it’s a very easy way to make bugs.

1 Like

Oh yeah, right. Didn’t notice!

So I tried it and the else part wasn’t working. What should I use instead?

What changes did you make, what does the code look like now?

local collectionservice = game:GetService("CollectionService")
local zones = workspace:WaitForChild("Zones")
local parts = collectionservice:GetTagged("Zone")
local tweenservice = game:GetService("TweenService")
local runservice = game:GetService("RunService")
local inside = false

local function inZone(zone)
	if not zone.Ambience.Ambience.Playing then zone.Ambience.Ambience:Play() end
	tweenservice:Create(zone.Ambience.Ambience, TweenInfo.new(0.2), {Volume = 1}):Play()
end

local function leftZone(zone)
	tweenservice:Create(zone.Ambience.Ambience, TweenInfo.new(0.2), {Volume = 0}):Play()
end

runservice.RenderStepped:Connect(function()
	for i, zone in pairs(parts) do
		local region = Region3.new(zone.Position - zone.Size/2, zone.Position + zone.Size/2)
		local regionparts = workspace:FindPartsInRegion3WithWhiteList(region, game.Players.LocalPlayer.Character:GetDescendants())
		for _, zoneregion in pairs(regionparts) do
			if zoneregion:FindFirstAncestor(game.Players.LocalPlayer.Name) then
				inZone(zone)
				print("in")
				break
			else
				leftZone(zone)
				print("out")
			end
		end
	end
end)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.