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

why does this script make my game crash?

Asked by
theCJarmy7 1293 Moderation Voter
8 years ago

im trying to make a game like cookie clicker, and i have the cookie that you click. but the first upgrade which will give you cookies per second, makes my game crash. its supposed to cost me 10 clicks. and then every second, it would give me one click.

script.Parent.Touched:connect(function()
    for _,Player in pairs(game.Players:GetPlayers()) do
        if Player:FindFirstChild("leaderstats") then
            Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value - 10
    end

    while true do
        if Player.leaderstats.Clicks.Value > 10
    then    Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value + 1
        wait(1)
        else print("not gonna happen")
    end
        end
    end
    end)

whenever i touch the part, it crashes studio. any fixes?

2 answers

Log in to vote
1
Answered by 8 years ago

So the reason studio crashed was because the fact you had no wait for your while true do loop. This is a better, more compact method of doing it

deb = false
script.Parent.Touched:connect(function(hit)

    if hit.Parent:FindFirstChild("Humanoid") and deb == false then

        local player = game.Players:GetPlayerFromCharacter(hit.Parent)
        if player.leaderstats.Clicks.Value >= 10 then
            deb = true
        player.leaderstats.Clicks.Value = player.leaderstats.Clicks.Value - 10

            while wait(1) do
                player.leaderstats.Clicks.Value = player.leaderstats.Clicks.Value + 1
            end
        end
    end
end)

As seen above I've probably used some methods you've never seen before. :GetPlayerFromCharacter() allows you to get the player from the character, which in this case is defined using hit.Parent, which should return the parent of Character

~~Hope i helped

Ad
Log in to vote
0
Answered by 8 years ago

Put the wait(1) outside of the if statement, otherwise if the player has less than 10 clicks that loop will try to run an infinite amount of times in 0 seconds.

    script.Parent.Touched:connect(function()
        for _,Player in pairs(game.Players:GetPlayers()) do
            if Player:FindFirstChild("leaderstats") then
                Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value - 10
        end

        while true do
               wait(1)
            if Player.leaderstats.Clicks.Value > 10
        then    Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value + 1
            else print("")
        end
            end
        end
        end)

Answer this question