Remote event firing both times randomly

So basically i have a local game pass script that fire if the player buy it but sometimes it fire both times and sometimes not, so i don’t have any idea of why it is not working

Here is the Client script:

local MPS = game:GetService("MarketplaceService")

local player = game.Players.LocalPlayer
local numberOfcoins = 20

script.Parent.MouseButton1Click:Connect(function()
	MPS:PromptProductPurchase(player, 1675468145)
	MPS.PromptProductPurchaseFinished:Connect(function(player, productId, WasPurchased)
		if WasPurchased == true then
			game.ReplicatedStorage.Remotes.Event.BuyCoins:FireServer(numberOfcoins)
			print("finished")
			wait(3)
		end
	end)
end)

And there is the server side script:

local RS = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")

RS.Remotes.Event.BuyCoins.OnServerEvent:Connect(function(player, price)
	local Coins = player:WaitForChild("leaderstats"):WaitForChild("Coins")
	Coins.Value = Coins.Value + price
	print(price)
end)

Please help me and explain me why

1 Like

You’re creating the event for PromptProductPurchaseFinished within the event, meaning whenever the player clicks, there is a new event created, and thus a new thread.

So when you click it for the second time, there are currently two threads listening to whether your gamepass was purchased, meaning the event is fired twice.

Place the PromptPurchaseFinished outside of the MouseClick event and you’ll be all good.

If you really want to keep it there, which I don’t recommend, considering you don’t even check the productId, make sure to disconnect the event once you’re complete.

1 Like

Ok i’ll try that and i say you if it works of not

Thanks you so much it works perfectly

1 Like

How do i disconnect the event ?

1 Like

You can define event connections as follows:

local eventConnection = event:Connect(function()

end)

You can find documentation here: RBXScriptConnection | Documentation - Roblox Creator Hub

Using that variable, you can call eventConnection:Disconnect() on it so it doesn’t take up memory. You should be aware though that when instances are destroyed, any events connected to those instances are disconnected. There is an execption when it comes to Players and Characters, though you can enable PlayerCharacterDestroyBehavior within the workspace.

And i do this on the client side script ? If it was me i would say in the server side but i’m not sure

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