Hey! Recently I have been implementing alot of corountine-heartbeat loops into my game as a replacement of the slow while true do
method. To the point that most of my scripts have 1 or even 2 of these loops. However, I am concerned if the thread somehow dies and the loop is killed.
Here is the basic structure of my loop:
coroutine.wrap(function()
game["Run Service"].Heartbeat:Connect(function()
end)
end)()
I have some ideas that might secure the loop if the worst comes. But I do not know if it is even needed.
Here is one of my scripts that have 2 loops:
--// UI
local RootGUI = script.Parent
--// UI parts
local SetBar = RootGUI.SettingsBar -- settings
local LevelBar = RootGUI.LevelBar -- levels
local CoinBar = RootGUI.CoinBar -- coins
local SettingsP = script.Parent.SettingsProper
--// just to make sure...
SettingsP.Visible = false
--// Levels
local LevelM = require(game.ReplicatedStorage.ModuleScripts.Levels)
local UserXP = game.ReplicatedStorage.PlayerData:WaitForChild(game.Players.LocalPlayer.UserId).Currency.Xp
local Bar = LevelBar.SelBar
local Levels = LevelM.Levels
local InfText = LevelBar.InfText
--// coin
local CCount = CoinBar.CoinAText
local UserCoin = game.ReplicatedStorage.PlayerData:WaitForChild(game.Players.LocalPlayer.UserId).Currency.Coin
--// Slider
local Slider = require(game.ReplicatedStorage.ModuleScripts.SliderM)
--// Level & coin function main
coroutine.wrap(function()
game["Run Service"].Heartbeat:Connect(function()
local xp = UserXP.Value
local UserLevel = LevelM.ConvertToLevel(xp)
local toS = 0
local NextLev = Levels[UserLevel]
if UserLevel > 1 then
toS = Levels[UserLevel-1]
end
local Spxp = xp-toS
local SpNextLev = NextLev-toS
local tot = 1*(Spxp/SpNextLev)
local perC = math.floor(tot*100)
InfText.Text = "Level "..UserLevel.." ("..perC.."%)"
CCount.Text = "₵ "..UserCoin.Value
Bar:TweenSize(UDim2.fromScale(1,tot),Enum.EasingDirection.Out,Enum.EasingStyle.Linear,.25)
end)
end)()
--// Settings
SetBar.Button.MouseButton1Click:Connect(function()
SettingsP.Visible = not SettingsP.Visible
end)
local PlrMouse = game.Players.LocalPlayer:GetMouse()
local BackgroundMS = SettingsP.AudioSettings.BackgroundM.SlideBase
local SlideConfig1 = {Start=0,End=1,Increment=0.05,DefaultValue=0.8}
local Slider1 = Slider.new(BackgroundMS,SlideConfig1,TweenInfo.new(0.1,Enum.EasingStyle.Linear,Enum.EasingDirection.Out),"X")
Slider.Track(Slider1)
local BSound = game.SoundService.BackgroundSound
--// Settings loop
coroutine.wrap(function()
game["Run Service"].Heartbeat:Connect(function()
for i, audio in pairs(BSound:GetChildren()) do
if audio.ClassName == "Sound" then
audio.Volume = Slider.GetValue(Slider1)
end
end
end)
end)()
The 2 loops have different purposes, 1 is for updating the amount of currency the player has, and then displaying it on a UI; and the other is just for the settings.
Although it is a vast improvement from while true do
loops, I am still sceptical that the loop thread could die.