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

Attempt to index nil with "Mainframe" error - how to fix?

I apologise for all the question I have been asking recently, but I just don't know how to fix half this stuff and google isn't helping much.

These scripts are for going from one Gui menu to another. They are pretty much the same script, yet one works and the other comes up with this nil error.

First script that works perfectly:

local CSMenu = game.Players.LocalPlayer.PlayerGui:FindFirstChild("CharacterSelect")
local CSelect = CSMenu.Mainframe
local Startmenu = game.Players.LocalPlayer.PlayerGui:FindFirstChild("StartMenu")
local SM = Startmenu.Frame

local function togglevis()
	SM.Visible = false
	CSelect.Visible = true
end
	
script.Parent.MouseButton1Click:Connect(togglevis)

Second script with Local variables changed to fit the next Gui, which doesnt work:

local ShopGui = game.Players.LocalPlayer.PlayerGui:FindFirstChild("Shop")
local Shopmenu = ShopGui.Mainframe
local Startmenu = game.Players.LocalPlayer.PlayerGui:FindFirstChild("StartMenu")
local SM = Startmenu.Frame

local function togglevis()
	SM.Visible = false
	Shopmenu.Visible = true
end

script.Parent.MouseButton1Click:Connect(togglevis)

The error received with this second script is: "Players.DragonessAnimations.PlayerGui.StartMenu.Frame.Shop.LocalScript:2: attempt to index nil with 'Mainframe'" It occurs on this line: local Shopmenu = ShopGui.Mainframe I honestly don't have the scripting knowledge to understand what this means, I am still trying to learn.

Any help is appreciated.

1 answer

✓ Accepted answer

ShopGui is nil, it does not exist or it did not replicated before the script has executed, for that use WaitForChild which will wait for the UI to replicate.

Example of using it:

local part = script.Parent
-- Will error in case the part is not loaded yet

local part = script:WaitForChild("Part")
-- Will yield until part is found, if the yield time exceeds 5 seconds or second argument of WaitForChild, it will throw you a warning.

-- in your case

local ShopGui = game.Players.LocalPlayer.PlayerGui:WaitForChild("Shop")

1 comment

0

I can't believe it was that easy, now I feel stupid lmao. Thank you!

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