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

why does this script make my game crash?

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

✓ Accepted answer

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

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)

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