Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why won't this Script find a GUI located in PlayerGui?

local data = game:GetService("DataStoreService")
local Level = data:GetDataStore("Level")
local Credits = data:GetDataStore("Points")
local XP = data:GetDataStore("XP")

game.Players.PlayerAdded:connect(function(plr)
---------------------------------------------------------------------------
	local key = "user_"..plr.userId
	
	local stats = Instance.new("IntValue",plr)
	stats.Name = "leaderstats"
	local level = Instance.new("IntValue",stats)
	level.Name = "Level"
	level.Value = Level:GetAsync(key) or 1
	if plr and plr.PlayerGui.LevelGui then
		game.Players[plr.Name].PlayerGui.LevelGui.Frame.Level.Text = "Level: " .. level.Value
	end
	local credits = Instance.new("IntValue",stats)
	credits.Name = "Credits"
	credits.Value = Credits:GetAsync(key) or 0
	if plr and plr.PlayerGui.LevelGui then
		game.Players[plr.Name].PlayerGui.LevelGui.Frame.Credits.Text = "Credits: " .. credits.Value
	end
	local xp = Instance.new("IntValue",stats)
	xp.Name = "EXP"
	xp.Value = XP:GetAsync(key) or 0
	
	level.Changed:connect(function() Level:SetAsync(key, level.Value) end)
	credits.Changed:connect(function() Credits:SetAsync(key, credits.Value) end) 
	xp.Changed:connect(function() XP:SetAsync(key, xp.Value) end)
-----------------------------------------------------------------------------
end)

Whenever I play the game, it gives me the error 'LevelGui is not a valid member of PlayerGui' on line 15, and even when I try printing the GUI in the console, it says that it was not found.

But I can clearly see the GUI on my screen???

Help is appreciated! Thanks! :D

1 answer

✓ Accepted answer

When you write plr.PlayerGui.LevelGui, you're already assuming that LevelGui exists. I know, I know. You do it inside of an if statement. That doesn't matter.

Before you can compare plr.PlayerGui.LevelGui to anything, it first must be accessed. Before I can compare my pencil to my pen, obviously I must go get my pencil. That's what the dot does. But if LevelGui doesn't exist, can the computer access it? Nope. Therefore it throws an error.

Basically, just remember that if you use a dot, you're assuming whatever you're looking for already exists.


Use FindFirstChild. This function will search for an object, then return true or false based on whether it found the aforementioned object.

if plr.PlayerGui:FindFirstChild("LevelGui") then

Alternatively, if you know that the object will eventually exist, you can use WaitForChild to wait until it exists.

local gui = plr.PlayerGui:WaitForChild("LevelGui")

This discussion is preserved as it was. New answers, comments, and votes are closed.