Post by Josh on Apr 30, 2017 20:04:37 GMT
StarterGui & PlayerGui
At some point, you might have tried to write a script that changes something in StarterGui to find that nothing happens until the player respawns.
This is because StarterGui is actually a bin. Every time a player spawns in your game, the contents of the bin get copied over into a folder that can be found inside every player called PlayerGui. This means that if you want to edit something that you stored in the StarterGui, you're going to need to find it in a player's PlayerGui.
How do I do this?
Accessing the PlayerGui is simple. Every player has their own, so you need to decide what you want to edit and where it will be.
Let's say that you want to change the Text property of a TextLabel called TextLabel stored in ScreenGui called ScreenGui that only JoshRBX can see. To do this, you need to access his PlayerGui folder. To access it, we will write the following...
game.Players.JoshRBX.PlayerGui.ScreenGui.TextLabel.Text = "Hello, world!"
We have now successfully changed the Text property of the TextLabel in JoshRBX's PlayerGui folder.
What if I want to change something in everyone's PlayerGui folder?
To change something in everyone's PlayerGui folder, you should iterate through every player in the game using a for loop.
Let's say that you want to change the Text property of a TextLabel called TextLabel stored in a ScreenGui called ScreenGui, but this time you want everyone to be affected. You should write something like the following to achieve this...
for _, v in pairs(game.Players:GetPlayers()) do
v.PlayerGui.ScreenGui.TextLabel.Text = "Hello, world!"
end
That's it, assuming you're not using FilteringEnabled.
How does that script work?
First, the script calls for a table that contains all players currently in the game.Players folder. The script then iterates through each one of these players in the table and sets the variable v to the player that the loop is currently at. For example, if there were two players, Player1 and Player2, then the v variable would first be set to the player, Player1, then the second player, Player2.
Assuming that we're currently at Player1 in the table, the script will go into that player's PlayerGui folder and change the Text property of the TextLabel. Then the script will do the same with Player2.
Hopefully, you now understand the difference between the two folders! Thank you very much for reading this explanation!
For more information on for loops, click here.