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

Why does my money drop give double each time?

Every drop gives double the last. Why is this happening? I only want it to give 100 to the player on each drop.


local timer = 180
local drop = script.Parent

while true do
	wait(1)
	timer = timer - 1
	
	if timer == 0 then
		drop.Anchored = false
		
		function take(Player)
			local Money = Player.leaderstats.Money
			local newtime = math.random(180,300)
			
			Money.Value = Money.Value + 100
			timer = newtime
			drop.Position = Vector3.new(-2, 158, 15)
			drop.Anchored = true
		end
	
		script.Parent.ClickDetector.MouseClick:Connect(take)
	end
end

5 comments

0

This should work...?

0

It works on the first drop then every drop after it doubles

0

I'd suggest suing a for loop as some advice, the format would be for i = 0,timer,-1 do. It will decrease by one increment automatically, and will stop running at 0

0

I just tried that and it tells me the script timed out

0

The ClickDetector.MouseClick event isn't being disconnected which is the problem, in other news move the take function out of the loop and make it local, there's no reason for it to be like that

1 answer

The reason as for why you get doble money each time is because you are having the event listener in a loop, which will add more and more listeners and will eventually just continue indefinitely.

Let me show you a coding example which you should not follow:

while true do
	ClickDetector.MouseClick:Connect( function (player)
		print("Clicked");
	end)
	wait(1)
end

You can try and run that code and you will see what happens after 10 seconds, it has made 10 event listeners, and you don't want this.

Instead you should do something like this (this is just an example):

while true do
	-- Any logic
	wait(1)
end

ClickDetector.MouseClick:Connect( function (player)
	-- Check if timer is 0
	if timer <= 0 then
		-- Do something
	end
end)

So pretty much turn your code into this:

local timer = 180
local drop = script.Parent

local function take(Player)
	
	-- Don't continue if timer is not 0 or less
	if timer > 0 then return end

	local Money = Player.leaderstats.Money
        local newtime = math.random(180,300)

        Money.Value = Money.Value + 100
        timer = newtime
        drop.Position = Vector3.new(-2, 158, 15)
        drop.Anchored = true
end

script.Parent.ClickDetector.MouseClick:Connect(take)

while true do
    wait(1)
    timer = timer - 1
	if timer == 0 then
		drop.Anchored = false
	end
end

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