What could be causing this code to run multiple times?

Very perplexing issue for me, but likely just my missing fundamentals of scripting:

The script is quite long, and I don’t think posting all of it is necessary to highlight my issue, but I can post more if needed.

I have a very long function called TrueUp that reconciles my game after each round of a player placing a part. All of this works fine. After nearly all times TrueUp is called it will reach the end, fire back to the client and they can place the next part. This happens until the player isn’t doing well and places a part such that the game should be over, in which case elements of TrueUp will set a local variable ‘GameOver’ to true, which changes a value ‘WinLossStatus’ and ends the game.

All of the code works fine and the game functions, but my question is this. When GameOver is true, the value “WinLossStatus” is being set to “Loss” as many times as TrueUp was called. This doesn’t make sense as I can see that my test prints only run a single time, it is the line(s) of code sandwiched between them that are running multiple times. How is this possible? (that the prints run once but code between them multiple times?)

	if GameOver == true then
		if Set == workspace.Set09 then
			print("Test 1")
			if workspace.Set09.WinLossStatus.Value == "" then
				print("Test 2")
				workspace.Set09.WinLossStatus.Value = "Loss"
				print("Test 3")
				workspace.Set10.WinLossStatus.Value = "Win"
				print("Test 4")
			end

Again, I know I’m not giving the full picture, but hoping someone might have thoughts on what could cause this?

Thanks!

Where are you binding an event to WinLossStatus.Changed? It’s likely that by mistake there’s been six connections listening for the Changed event, hence six print statements for one assignment.

Are you making a new connection every time the game is over?

1 Like

This may be my issue, but I still don’t quite understand why.

To your point, my listener, which calls another function: BattleSetReset, is inside of my TrueUp function. Would the change it self, which triggers this listener, actually change as many times as the listener was run by the original function?

	workspace.Set09.WinLossStatus.Changed:Connect(function()
		print("Set09.WinLossStatus was changed to: ",workspace.Set09.WinLossStatus.Value)
		if workspace.Set09.WinLossStatus.Value == "Win" then 
			BattleSetReset(workspace.Set09,Player,"Win")
		elseif workspace.Set09.WinLossStatus.Value == "Loss" then
			BattleSetReset(workspace.Set09,Player,"Loss")
		end
	end)
1 Like

You were spot on - even without seeing the code - Very rookie error. This was driving me nuts; thank you so much.

Lesson if any fellow rookies run across this: You can not have listeners (.changed:Connect…) within a function that runs many times.

2 Likes