Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is the value adding more than it should even with debounce?

I'm making a test project where if you step on a block it will either give you money or take away money, whichever one happens is completely randomized. It will either give you 200-600 money or take it away. Here is the code:

local ChangeMoney = {200, 300, 400, 500, 600}
local isTouched = false -- debounce

game.Players.PlayerAdded:Connect(function (player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Parent = player
	leaderstats.Name = "leaderstats"
	
	Money = Instance.new("IntValue")
	Money.Parent = leaderstats
	Money.Name = "Money"
	Money.Value = 1000
	
end)

workspace.ChanceMoney.Touched:Connect(function (hit)
	local ChanceValue = math.random(1, 2) -- Gives money if 1, takes if 2
	if game.Players:GetPlayerFromCharacter(hit.Parent) then
		if not isTouched then
			isTouched = true
			for i, v in pairs(ChangeMoney) do
				local RandIndex = math.random(1, 5) --For ChangeMoney's index
				if ChanceValue == 1 then
					if Money.Value > 0 and i == RandIndex then
						Money.Value -= v
						elseif Money.Value <= 0 then -- Preventing money to be negative
						Money.Value = 0
					end
				elseif i == RandIndex and ChanceValue == 2 then
					Money.Value += v
				end
			end
			wait(5)
			isTouched = false
		end
	end
end)

The thing is it works, but not as expected. Even if it's not under the table, it somehow adds random numbers to the value (even with debounce on). I could have 1,000 dollars and when I step on it I could get 1,900, 2,100, 1,700, etc. Those numbers are not listed under the table, and I'm not sure how it adds more than it should. It's the same with subtracting. I could have 1,000 and somehow end up with 100 dollars. I don't think it's all the numbers combined, as the integers in ChangeMoney all added up is 2000, and the result is usually not the sum of that. Wondering how to get this fixed.

1 answer

✓ Accepted answer

Try putting local RandIndex = math.random(1, 5) outside of the for loop. Put it after the istouched = true

5 comments

0

Thank you! Can you explain a bit of what happened when I put it in the for loop?

0

This is because it finds a new number every time the loop runs. When you put it on the outside, it picks one number while in the inside it picks multiple numbers.

0

For example if you put it on the outside, the random number is one, the loop runs through 1,2,3,4,5 and there is only 1 one so it fires once.

0

If you put it in the inside, there will be multiple numbers like 1,4,5,4,5. 1 corresponds with 1, 4 corresponds with 4 and 5 corresponds with 5 causing it to run 3 times. Sorry if this explanation is confusing

0

I got it, thanks!

This discussion is preserved as it was. New answers, comments, and votes are closed.