Function not reacting to PlayerAdded

So what I’m trying to do is test a loading screen concept. When the player joins the game, the gui pops up, you wait a little bit, then press the play button. I’ve managed to make the gui close when you press the Play button, but when it comes to popping up, it’s not working. I’m making this a 1 player game, so i don’t need to worry about local things just yet. here’s my script.

Button = game.StarterGui.Loading.Frame.TextButton
Gui = game.StarterGui.Loading
function close()
	script.Parent.Parent:Destroy()
end
function popup()
	print("this function is running")
	game.StarterGui.Loading.Frame.Loaded.Value = false
	Gui.Enabled = true
	script.Parent.Text = ("Loading...")
	wait(math.random(1, 10))
	game.StarterGui.Loading.Frame.Loaded.Value = true
	script.Parent.Text = ("Play")
	script.Parent.MouseButton1Click:Connect(close)
end
game.Players.PlayerAdded:Connect(popup)

Your script is directly refering to the template Gui stored in game.StarterGui, while upon connecting to the game the Gui that the player actually sees is stored in game.Players.LocalPlayer.PlayerGui

All ScreenGui’s stored in StarterGui are copied to the PlayerGui folder upon entering the game. Therefor, when you want to make changes to the Gui displayed to a player, you need to make the correct reference to the Player-Specific copy of your Gui.

Try something like this;

local Player = game:GetService("Players").LocalPlayer
local PlayerGui = Player.PlayerGui

LoadingGui = PlayerGui.Loading
Button = PlayerGui.Loading.Frame.TextButton

function close()
	script.Parent.Parent:Destroy()
end
function popup()
	print("this function is running")
	LoadingGui.Frame.Loaded.Value = false
	LoadingGui.Enabled = true
	Button.Text = ("Loading...")
	wait(math.random(1, 10))
	LoadingGui.Frame.Loaded.Value = true
	Button.Text = ("Play")
	script.Parent.MouseButton1Click:Connect(close)
end

popup()

You should be triggering this code in a LocalScript, one you can parent either to Player.PlayerGui (by placing it in StarterGui) or Player.PlayerScripts (by placing it in StarterPlayerScripts). Since this code runs on the player client, it will only start running once the player has joined the server. Therefor, Instead of listening to PlayerAdded, you can just call the popup method to start the loading gui.

3 Likes

Thanks! I seriously need to know the difference between local and normal scripts.