Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why does my money drop give double each time?

Asked by 5 years ago

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
0
This should work...? NewGPU 36 — 5y
0
It works on the first drop then every drop after it doubles JJBIoxxer 50 — 5y
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 Ziffixture 6913 — 5y
0
I just tried that and it tells me the script timed out JJBIoxxer 50 — 5y
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 Vulkarin 581 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago

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

Ad

Answer this question