3 minutes
Add an Inspector Component
Let's walk through building a Babylon Inspector component system that lets you toggle the debug tools in your game. We'll break down the code and explain how each part works.
Setting Up the Inspector Imports
First, we need to import the Babylon debug tools and our ECS framework:
The first two imports pull in Babylon's debug layer and inspector UI. These are side-effect imports that register the inspector functionality globally.
Inspector Options
Next, we define what configuration our inspector component needs:
We need to know which HTML element will contain the inspector and which key will toggle it on and off.
Creating the Inspector Component
Now we build the component class that holds our inspector configuration:
The component stores the debug layer container ID and trigger key. We provide sensible defaults - "debugLayer" for the container and "Backquote" (the backtick key) for toggling.
Setting Up the Inspector System
The system handles the inspector logic. Let's start with the constructor:
This tells the system to process any entity that has an InspectorComponent attached.
Loading the Inspector Entity
When an entity with an inspector component gets added, this method sets up the keyboard listener:
We grab the inspector component and extract the trigger key and debug layer ID we'll need.
Setting Up the Keyboard Toggle
Next, we create the keyboard event listener:
We listen for keydown events globally. When our trigger key is pressed, we make sure the canvas has focus and check if it's the right key.
Toggling the Inspector Visibility
Finally, we handle showing and hiding the inspector:
If the debug layer is already visible, we hide it. Otherwise, we show it with overlay mode enabled and embed it in our specified HTML element.
Why no processEntity method?
You'll notice this is a pretty small system, with only something to do in the loading phase. It has no processEntity method, so it's skipped every frame. This is perfectly useful without being in a gameloop, because we use the browser's keypress event to update it's visibility.
In Sum
This inspector system gives you a toggle-able Babylon.js debug interface. Press the backtick key (or your custom trigger key) to open the inspector and explore your scene, check performance, modify materials, and debug your game. The inspector appears as an overlay that doesn't interfere with your game's UI, making it perfect for development and debugging.