i have a serialization script which serializes inventory items, but there is a function linked to playeradded which causes errors because the serialize functions haven’t run yet. How would I wait until these are done to run the playeradded functions? *in a secure way
Use a coroutine and a boolean value to tell that the function has been run.
local runService = game:GetService('RunService') local hasBeenRun = false coroutine.wrap(function() -- do the serialization func hasBeenRun = true end)() -- ensure you have this extra set of brackets as it calls the coroutine players.PlayerAdded:Connect(function() repeat runService.Heartbeat:Wait() until hasBeenRun end)
Coroutines have a state which you can read to see whether the thread has been executed.
coroutine.create to create a thread object that can be interacted with instead of relying on an external variable to check the state of the thread.
In this case it would also make more sense to create your own event control–maybe using Bindables–so you can have a linear flow of how the code will be executed. Promises can do this nicely.