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.
01 | script.Parent.Touched:connect( function () |
02 | for _,Player in pairs (game.Players:GetPlayers()) do |
03 | if Player:FindFirstChild( "leaderstats" ) then |
04 | Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value - 10 |
05 | end |
06 |
07 | while true do |
08 | if Player.leaderstats.Clicks.Value > 10 |
09 | then Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value + 1 |
10 | wait( 1 ) |
11 | else print ( "not gonna happen" ) |
12 | end |
13 | end |
14 | end |
15 | end ) |
whenever i touch the part, it crashes studio. any fixes?
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
01 | deb = false |
02 | script.Parent.Touched:connect( function (hit) |
03 |
04 | if hit.Parent:FindFirstChild( "Humanoid" ) and deb = = false then |
05 |
06 | local player = game.Players:GetPlayerFromCharacter(hit.Parent) |
07 | if player.leaderstats.Clicks.Value > = 10 then |
08 | deb = true |
09 | player.leaderstats.Clicks.Value = player.leaderstats.Clicks.Value - 10 |
10 |
11 | while wait( 1 ) do |
12 | player.leaderstats.Clicks.Value = player.leaderstats.Clicks.Value + 1 |
13 | end |
14 | end |
15 | end |
16 | 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.
01 | script.Parent.Touched:connect( function () |
02 | for _,Player in pairs (game.Players:GetPlayers()) do |
03 | if Player:FindFirstChild( "leaderstats" ) then |
04 | Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value - 10 |
05 | end |
06 |
07 | while true do |
08 | wait( 1 ) |
09 | if Player.leaderstats.Clicks.Value > 10 |
10 | then Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value + 1 |
11 | else print ( "" ) |
12 | end |
13 | end |
14 | end |
15 | end ) |