Problem
This is because all code in your game runs sequentially, even while in different scripts. Everything is managed by ROBLOX's thread scheduler, which decides which "threads" of code to execute next, giving the illusion of concurrency. Long story short, ROBLOX has decided to run the code in your "second script" before the code in your "first script". Thus, trying to print _G.preGame before it was ever registered.
Solution
Anything that yields (including the yield function directly from the coroutine library), will ensure that the designated thread will be pushed to the back of the scheduling queue, meaning whatever is before it will run first. It's essentially a "pause" on the yielded thread, only to later get resumed automatically. Yield functions include wait, WaitForChild, or anything else that calls coroutine.yield under the hood. For instance:
Example 1:
coroutine.yield()
print("End")
Example 2:
print("Start")
The examples above quickly demonstrates how ROBLOX treats yielded threads, seeing that "Start" will always print before "End", because that coroutine is now temporarily suspended, allowing "Start" to print first.
Better solution
A better solution would be to not use _G at all. There are much better ways of having code in different scripts communicate with each other, the most credible being remotes. Remotes are special objects that allow you to bind functions to arbitrary events, creating your own event listeners. There are essentially two different kinds of communication with said remotes, and two different kinds of remotes depending on the communication:
Remote Events
Bindable Events
- Used for the exact opposite. Not compatible with network communication, can only be used for firing events on the same side of the network (server-to-server, or client-to-client). ROBLOX Wiki article
These may be tricky to work with at first, but they make much more sense and become very enjoyable to work with later on. Let me know if you need help better understanding any of them.
Functions
There's also another feature optimized for different, more specific tasks, which involve single functions as callbacks. Instead of sending information instantly (without yielding), Remote/Bindable functions will invoke it's event listener and yield (wait) until the callback function returns something or terminates. This is a nice contrast to remote events, where you cannot return anything directly once fired. It all depends on what you want to do. See BindableFunctions | See RemoteFunctions.
1 comment
Hey! Sorry for the late response. So when experimenting I found that the first script runs before the second one. The only difference in these two scrips is that the first one is a regular script and the second one is a LocalScript. Would that have to do with anything? Thank you!