Search code examples
functionluawaitroblox

How do i make the game wait until a funcion is called?


I was creating a script and i want to know how do i make the game wait until a funcion is called If someone awnser me,ill be thankful


Solution

  • Firstly do not use loops, use events!

    To wait for an event to happen you can use the wait method, like so:

    print("Starting to wait for touch")
    workspace.Part.Touched:Wait()
    print("Touched!")
    

    This will wait for the part to be touched before it continues the script. But ofcourse, other scripts will still run, the game is not "paused", it is just that script's execution that is suspended until the event is fired.

    You can also make custom "wait for call" by using for example a BoolValue like so:

    local WaitObject = Instance.new("BoolValue")
    
    function WaitOn()
        WaitObject.Changed:Wait()
    end
    
    function StopWait()
        WaitObject.Value = not WaitObject.Value
    end
    

    You can also place the BoolValue in the game and do the wait and stop wait in separated scripts. If you do it in same script, remember to use different threads