Getting the PlayerGui with roblox-ts

So, I’ve been using roblox-ts for a bit now and it’s more difficult than I thought.

  • Currently, I’m making a TopBarUI for my game and making the show menu button (which shows a menu on click). I’m trying to get the PlayerGui with some children parenting a ScreenGui named “TopBarUI”. I created a local script (with the .client.ts ending in VS Code) which is parented with the StarterGui. So I began writing the code of what I thought would work. After writing this TypeScript code (as seen in the attachment below),

    this error ('PlayerGui' is possibly 'undefined') about the PlayerGui kept popping out. I looked into the Player Instance and it doesn’t have a PlayerGui.

  • I tried writing a file with a .d.ts ending to index children.

    And obviously, it didn’t work.

  • Also, here’s the tree map of the ScreenGui (and the children) in Roblox Studio. I didn’t add the others because they weren’t important for now.Screenshot 2024-04-13 at 10.09.04 PM

Appreciate anyone who helps me resolve this big of a problem.

Code samples in case you want to copy and paste.
import { Players } from "@rbxts/services";

const Player = Players.LocalPlayer;
const PlayerGui = Player.FindFirstChildOfClass("PlayerGui");

const TopBarUI = PlayerGui.TopBarUI;
interface PlayerGui extends Instance {
	TopBarUI: ScreenGui & {
		Background: Frame & {
			ShowMenuButton: Frame & {
				Background: Frame;
				Button: ImageButton;
			};
		};
	};
}
1 Like

Try using WaitForChild, if I’m not mistaken PlayerGui may take some time to load.

1 Like

It works very well now, with no errors found. Well, thank you so much for solving this issue!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.