I have a script, It has 1 while loop so every __ seconds it will give mana. The number of seconds depend on the player's level. I want the player's level to go up every minute they play the game. Please help!
game:GetService("Players").PlayerAdded:connect(function(plyr) local stats = Instance.new("IntValue", plyr) stats.Name = "leaderstats" local lvl = Instance.new("IntValue", stats) lvl.Name = "Level" lvl.Value = 1 local mana = Instance.new("IntValue", stats) mana.Name = "Mana" mana.Value = 0 while wait(1/lvl.Value) do mana.Value = mana.Value+1 end end)
By using delta time, you can synchronize the two events separately within the same loop:
game:GetService("Players").PlayerAdded:connect(function(plyr) local stats = Instance.new("IntValue", plyr) stats.Name = "leaderstats" local lvl = Instance.new("IntValue", stats) lvl.Name = "Level" lvl.Value = 1 local mana = Instance.new("IntValue", stats) mana.Name = "Mana" mana.Value = 0 local last = tick() local elapsed = 0 local otherElapsed = 0 while true do local t = tick() local dt = t - last last = t elapsed = elapsed + dt otherElapsed = otherElapsed + dt local manaUp = (1/lvl.Value) if otherElapsed > manaUp then while otherElapsed >= manaUp do -- It's possible for the minimum wait to be *more* than the time it takes to gain mana. mana.Value = mana.Value + 1 otherElapsed = otherElapsed - manaUp end end if elapsed > 60 then --one minute lvl.Value = lvl.Value + 1 elapsed = elapsed - 60 end wait() end end)
In order to break out of a loop, you would do something like this:
while true do wait() break end
game:GetService("Players").PlayerAdded:connect(function(player) local stats = Instance.new("IntValue",player) --tabbing is unecessary stats.Name = "leaderstats" local lvl = Instance.new("IntValue",stats) lvl.Name = "Level" lvl.Value = 1 local mana = Instance.new("IntValue",stats) mana.Name = "Mana" coroutine.resume(coroutine.create(function()--coroutines! They let you run functions on a separate thread, meaning other code can run at the same time. while wait(60) do lvl.Value = lvl.Value + 1 end end)) while wait(1/lvl.Value) do mana.Value = mana.Value + 1 end end)