Why does this code sometimes work and sometimes doesn't

I have a code where if the player presses a Button the players team changes but sometimes it works and sometimes it doesn’t I have can make an easier version with a code in each button but I want to keep it small as possible

The Code
local UserId = game.Players.LocalPlayer.UserId
local player = game.Players:GetPlayerByUserId(UserId)

local CS = game:GetService("CollectionService")
local Buttons = CS:GetTagged("Groups")

local Holder = script.Parent

for _, Button in pairs(Buttons) do
	wait()

	Button.MouseButton1Click:Connect(function()
		print(Button.Name)
		if player:IsInGroup(Button:FindFirstChild("GroupId").Value) then
			print("Player Is In Group")
			player.Team = game.Teams.Teams:FindFirstChild(Button)
		else
			print("No")
			player.Team = game.Teams:FindFirstChild(Button.Name)
			print(player.Team)
		end
	end)
	
end

Is this a local script or a server script?

It’s a local script inside StarterGui.

You should use Remote event then because it’s not going to replicate to other users or basically not work for everyone So even if you fix the bug happening Right now it won’t work.

If you don’t know where to start here is a Head-Start: