For i,v in pairs loop not working

So basically, I made portals in my game. To use the portals you must go near the portal and a gui will appear telling the player to press E to use the portals. Since I didn’t wanna use elseif statements to check what portal the player used I just used for i,v in pairs loop. But for some reason the event where you press E when near the portal works for every portals but it doesn’t show the gui that tells the player to press E. It only shows that gui in one of the portals (The yellow portal). Here is a footage of me testing my game and going near the portals.


I don’t really know what’s wrong with my script but here is the source of the script

local UIS = game:GetService("UserInputService")

-- The line of code that works.
UIS.InputEnded:Connect(function(Input)
	if Input.UserInputType == Enum.UserInputType.Keyboard or Input.UserInputType == Enum.UserInputType.Gamepad1 then
		if Input.KeyCode == Enum.KeyCode.E or Input.KeyCode == Enum.KeyCode.ButtonY then
			if UIS:GetFocusedTextBox() == nil then
				for i,v in pairs(workspace.Portals:GetChildren()) do
					local Distance = (v.Body.Position-game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart").Position).Magnitude
					if Distance <= 10 then
						game.ReplicatedStorage.PurchaseLand:FireServer(v.TeleportTo,string.sub(v.Name,1,#v.Name - 1),v.Cost.Value,v.Body.Color)
					end
				end
			end
		end
	end
end)

-- The line of code that is sort of broken? idk bc it works on the yellow portal
workspace.CurrentCamera.Changed:Connect(function()
	for _,Portal in pairs(workspace.Portals:GetChildren()) do
		local Distance = (Portal.Body.Position-game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart").Position).Magnitude
		if Distance <= 10 then
			script.Parent.Parent.Adornee = Portal.Body
			script.Parent.Visible = true		
		else
			script.Parent.Visible = false	
		end
	end
end)

When you press E when near any portals it would teleport you to another land as expected but It doesn’t show the gui that tells the player to press E. It only shows the gui when near the yellow portal but the rest of the portal it doesn’t show the gui it just teleports the player to another land when they pressed E

1 Like

The reason it works on one portal is probably because that portal is the last one in the loop. It sets Visible to false if the last one in the loop isn’t close enough, regardless of the others’ distances. I would either break the loop once you set the Adornee and visibility (just put break before the else), or only set Visible to false before the loop happens instead of doing it for every portal.

4 Likes

for some reason that tip made it work! Thank you so much! Now it shows the gui when near every portals! Thanks! :smiley: