Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How can I make my main script wait for a local script to stop running?

To give you some context of my game is that I have a main script that does most of the code in it and local scripts awaiting to be activated by RemoteEvents. One thing I ran into is the fact that I need one of my local script needs to be running for about 5+ seconds while the main script needs to wait for it to be finished. Once the local script is finished, the main script continues to move on. At first, I was thinking running the code like this:

Main Script:

--Code...
--Code...
--More Code...

local rep = game:GetService("ReplicatedStorage")
rep.RemoteEvent1:FireAllClients()

repeat wait() until rep.RemoteEvent2:OnServerEvent:Connect(function()
	--Continue with code
end)

Local Script:

local rep = game:GetService("ReplicatedStorage")

rep.RemoteEvent1.OnClientEvent:Connect(function()
	--Code
	rep.RemoteEvent2.FireServer()
end)

This way I am able to wait for the local script to be finished so that the main script could run again. It seemed like a sure proof plan to me but after I tried it, it skipped over it and did not wait for the local script to finish! What should I do?

2 comments

0

?

0

Repeat until loops repeat code until a certain condition is met. OnServerEvent:Connect() returns an RBXScriptConnection, which will immediately break the loop, as ANY value that is not nil or false is considered truthy in boolean context. So remove the repeat loop.

1 answer

What you are looking for is the Wait method of the scriptsignal.

This will essentially "pause" the script until the signal attached to the wait is activated

Change your main script to this

--Code...
--Code...
--More Code...

local rep = game:GetService("ReplicatedStorage")
rep.RemoteEvent1:FireAllClients()

rep.RemoteEvent2.OnServerEvent:Wait()
--Continue with code

This should fix your issue, but I do recommend using a different method since this entire process seems inefficient. You could set up a connection on the server and wait for the client to fire it instead.

Hope this helped!

2 comments

0

What other method should I use then? Could you maybe suggest me a few?

0

The one I recommend is having an event setup on the server that when fired says "hey, the server can run this code now". Then when the client joins they fire it whenever they want to in order to run it

This discussion is preserved as it was. New answers, comments, and votes are closed.