Improving 2 Functions Connected to `RunService.Heartbeat`

I have a ModuleScript module script and a Script normal script that each have a function (I’ll refer to both of those functions as HeartbeatFunctions). Both HeartbeatFunctions will eventually be connected to RunService.Heartbeat. The HeartbeatFunction in ModuleScript sets variables that the one in Script relies on to work. When the corresponding event fires, Script will call ModuleScript to connect ModuleScript’s HeartbeatFunction before connecting its own HeartbeatFunction.

Initially, I had a problem where Script’s HeartbeatFunction would run before ModuleScript’s, which would throw an error since the variables were nil. I fixed this by adding task.wait(0.001) in between those two lines like so:

ModuleScript.connectHeartbeatFunction()
task.wait(0.001)
RunService.Heartbeat:Connect(HeartbeatFunction)

For now, it works, but I feel like this is an unreliable way to silence that error. I can’t use an if statement because I want Script’s HeartbeatFunction to connect the first time the corresponding event fires. I imagine that if I used an if statement, the event would have to fire again in order to connect, which is something I want to avoid.

All in all, my question is whether or not there is a way to stop Script from running until ModuleScript successfully connects and runs ModuleScript’s HeartbeatFunction once before resuming with execution.

You can simply yield the “connectHeartbeatFunction”, until the variables are no longer nil.

While trying to figure out how to tell my scripts when to call coroutine.resume (which is what I assume Skainted was hinting at), I found the Wait RBXScriptConnection method. I went with this way because it meant I could keep Script’s original code.

For anyone who somehow runs into this very specific problem, ModuleScript actually sets variables in another module script. I added a bindable event (I’ll refer to it as BindableEvent) to that variable-holding module script and added BindableEvent.Event:Wait() to the end of ModuleScript.connectHeartbeatFunction so that Script continues running only after BindableEvent fires. BindableEvent itself fires when the necessary variable changes. This still carries the problem of firing every single heartbeat, but at least I won’t have to deal with calling coroutine.create in every script that calls ModuleScript.connectHeartbeatFunction.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.