Gui isn't a valid member of PlayerGui

I am working on a script that when you press a button, it will go to another screengui and will enable a frame inside of it. However, I keep getting the same error and I am stuck and don’t know what to do.

Here is the error message I keep receiving:

Here is my code:

local CloseButton = script.Parent
local Wallpaper = script.Parent.Parent.Parent.Parent.Windows95.WallPaper


CloseButton.MouseButton1Click:Connect(function()
	script.LeaveSound:Play()
	wait(0.1)
	Wallpaper.Visible = true
end)

ScreenGuis are streamed into existence when the player first spawns (assuming default settings). Because of this, your LocalScript might actually run before certain items in your Gui exist yet (in a way, they haven’t downloaded yet). It usually only takes a couple frames at most, but it still takes some time.

To get around this, you can use WaitForChild, which will wait until a certain object exists. Also, to clean up your code, it’s probably better to reference down the tree from the player object, rather than chaining a bunch of Parent.Parent.Parent... stuff:

local player = game:GetService("Players").LocalPlayer
local CloseButton = script.Parent

-- WaitForChilds added for Windows95 and WallPaper (not needed for PlayerGui since it exists immediatley)
local Wallpaper = player.PlayerGui:WaitForChild("Windows95"):WaitForChild("WallPaper")

CloseButton.MouseButton1Click:Connect(function()
	script.LeaveSound:Play()
	wait(0.1)
	Wallpaper.Visible = true
end)

The reason you don’t need it for the CloseButton is because it’s the parent of the script. So the script won’t exist unless that button exists first.

5 Likes

Thank you so much! This makes a ton of sense and helps me out.

2 Likes