I am attempting to add premium benefits to my game, using the following code:
cash.Changed:Connect(function()
if player.MembershipType == Enum.MembershipType.Premium then
cash.Value = cash.Value + (cash.value * .01)
end
end)
This code checks for when the Player’s cash changes, and adds extra cash to their balance.
The issue that I having is that this works whenever the player buys something with their cash as well. So they loss the money from the purchase, and then receive extra cash from the code.
Basically I need a way to check if the balance increase, and only have the code run if they are gaining money. However, I am not sure how to check if their money is increasing or decreasing.
You’d likely want to use some sort of client-server event for when a player is purchasing or earning money. Instead of binding this function to cash.Changed, bind it to your own RemoteEvent.
That way you don’t even need to check if the player lost or earned money, you already know which it was based on which event fired.
local lastCash = cash.Value
cash.Changed:Connect(function()
-- check if we gained cash
if cash.Value > lastCash then
if player.MembershipType == Enum.MembershipType.Premium then
cash.Value = cash.Value + (cash.value * .01)
end
end
lastCash = cash.Value
end)
You could check if the new balance is greater than the current one (assuming that when they buy more currency their cash value will rise), and if it is, it will double
cash.Changed:Connect(function(new)
if player.MembershipType == Enum.MembershipType.Premium then
if cash.Value >= new then
cash.Value = cash.Value + (cash.value * .01)
end
end
end)
You can just add a debounce, and you should also probably use GetPropertyChangedSignal instead of Changed
local lastCash = cash.Value
local debounce = false
cash:GetPropertyChangedSignal'Value':Connect(function()
if debounce then return end
if cash.Value > lastCash then
debounce = true
if player.MembershipType == Enum.MembershipType.Premium then
cash.Value = cash.Value + (cash.Value * .01)
end
debounce = false
end
lastCash = cash.Value
end)
Why bother with all the extra code when you can just bind the same functionality to a RemoteEvent and call that when the player earns cash? Using cash.Changed or cash:GetPropertyChangedSignal is just bloat.
cashEarned.OnServerEvent:Connect(function()
if player.MembershipType == Enum.MembershipType.Premium then
cash.Value = cash.Value + (cash.Value * .01)
end
end)
There is no need to create extra variables to compare the before and after of the cash value if the function is bound to an event that only fires when the player earns cash.