Don't know where to add my gamepass script in my leaderstats

I have made a gamepass and did everything else, and now I have to give the player the “powers”. The gamepass is x2 coins for the simulator game I am making, but I do not know where to put the script in. I have already tried putting the gamepass script under the

while true do
wait(20)`
leaderstats.Coins.Value = leaderstats.Coins.Value + 20 --this works every 20 seconds`

--My script is below
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("Coins")

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local Coins = Instance.new("IntValue")
	Coins.Name = "Coins"
	Coins.Value = DataStore:GetAsync(player.UserId) or 0
	Coins.Parent = leaderstats
	
	while true do
		
				wait(20)
		leaderstats.Coins.Value = leaderstats.Coins.Value + 20
			end
		
		
		
	end)
	
	
	
	
	

	
	

game.Players.PlayerRemoving:Connect(function(Player)
	DataStore:SetAsync(Player.UserId, Player.leaderstats.Coins.Value)
end)

Try and use Coins.Changed event to detect when the coin value in the player changes.

--Store the last time you made money
local lastC = Coins.Value
Coins.Changed:connect(function()
	--if the different between your money now and how much money you had before is greater than 0 you made money; double money base on if you got gamepass
	if (Coins.Value-lastC) > 0
		and --Replace this line and add your gamepass checker here 
	then
		--Double money
		Coins.Value = Coins.Value * 2
	end
	--Update this value so we can use it again to check if you gain or lose money later
	lastC = Coins
end)

This basically gets called whenever the Coins value change, since we don’t know if you gain or lose money there is another variable called lastC which stores what money you had before something happened to your money. Now in the event, we’re going to see if you gain or lose money, we do this by taking your new money value and minus it by the old one. If you gain money, the result of this should be a positive number. For example, if we start off with 5 dollars then we gain 20, the code will fire the event and minus 20 from 5 returning 15 and passing the first check of the if statement. the next check is base on you and how you check for the gamepass. If all that works then we take your money and double it. after the event is all done we make sure to update the lastC value to make sure it’s ready to be used again the next time something happens to the Coins. Make sure the code is place BEFORE your while loop because anything after the while loop won’t work because the while loop is yielding all code until it finishes and since you set ots end condition to true it will not stop ever. I’m just making sure you know this because I make the same mistake before. Hope this helps

1 Like