Hello guys. Let’s say I have 2 regular scripts and 1 module script:
--Script 1
local Module = (ReplicatedStorage.Module)
Module.Initialize()
--Script 2
local Module = (ReplicatedStorage.Module)
Module.Initialize()
--Module
local Module = {}
function Module.Initialize()
Module.CreateProblem()
end
function Module.CreateProblem()
RunService.RenderStepped:Connect(function(Delta) ... end)
end
In the simplified example above, you can see that 2 scripts require same module script, and it will create 2 RunService connections. But what if I need only 1 RunService connection? What’s best way to do this? Make some attribute variable and set it to true after first connection? Restructure code (how?)?
Extra notes:
That’s simplified example. There’s possiblity of 10s of scripts requiring such module.
You could check if the RenderStepped Connection has already been made.
--Module
local Module = {}
local RsConnection
function Module.Initialize()
Module.CreateProblem()
end
function Module.CreateProblem()
if not RsConnection then RsConnection=RunService.RenderStepped:Connect(function(Delta) ... end) end
end
If you only want an entire function to run once then
--Module
local Module = {}
local FunctionActive=false
function Module.Initialize()
Module.CreateProblem()
end
function Module.CreateProblem()
if FunctionActive then return end
FunctionActive=true
RunService.RenderStepped:Connect(function(Delta) ... end)
end
When module required, it’s code not shared. Due to this, if single module was called twice, it will be executed from beginning twice, resulting in doubled connected functions. That’s why I did this topic. Everything isn’t that easy.
local module = {}
local Module = {}
local isProblemCreated = false
function Module.Initialize()
if not isProblemCreated then
Module.CreateProblem()
isProblemCreated = true
else
warn("Module.CreateProblem() has already been called.")
end
end
function Module.CreateProblem()
-- Your existing code inside CreateProblem function
print('Problem')
end
return Module
Hm, seems strange to me, because when I tested in game, module have decided to run code twice. Simpler test-case like your really gives valid result. I’ll try to look why