TGB/MiniTutorials/Your First Dynamic GUI Tutorial

From TDN

The purpose of this tutorial is to show you how to build a GUI dynamically. When you build a GUI dynamically, you take multiple GUI objects and "patch" them together into one GUI.

Create Your GUI Objects

First, let's create your GUI objects and plug them into your game. Unlike the previous tutorial, Your First GUI Tutorial, I am going to show you how to create your GUI objects using code, not the GUI Editor.

  1. Navigate to your project's gui folder.
  2. Create a text file called dynamicmenu.gui.
  3. Open dynamicmenu.gui in a text editor, and paste in the following code:
    new GuiControl(dynamicmenuGui) {
       canSaveDynamicFields = "0";
       Profile = "GuiDefaultProfile";   
       HorizSizing = "right";
       VertSizing = "bottom";
       position = "0 0";
       Extent = "1024 768";
       MinExtent = "8 2";
       canSave = "1";
       Visible = "1";
       hovertime = "1000";
    };
    
    new GuiControl(backgroundGui) {
       canSaveDynamicFields = "0";
       Profile = "GuiWindowProfile";     
       HorizSizing = "right";
       VertSizing = "bottom";
       position = "346 104";
       Extent = "508 411";
       MinExtent = "8 2";
       canSave = "1";
       Visible = "1";
       hovertime = "1000";
    };
    
    new GuiButtonCtrl(exitGUI) {
       canSaveDynamicFields = "0";
       Profile = "GuiButtonProfile";
       HorizSizing = "right";
       VertSizing = "bottom";
       position = "815 476";
       Extent = "30 30";
       MinExtent = "8 2";
       canSave = "1";
       Visible = "1";
       Command = "menu::exit(shopGui);";
       hovertime = "1000";
       text = "x";
       groupNum = "-1";
       buttonType = "PushButton";
    };
    
  4. Save dynamicmenu.gui.
  5. In your project folder, open main.cs.
  6. Add the following line in initializeProject() near the top: exec("~/gui/dynamicmenu.gui");
  7. Save main.cs. You can now reference your GUI objects in your game.

Dynamically Generate a GUI

Now, lets use our GUI objects to dynamically generate a GUI in your game.

  1. In your project folder, open game.cs in a text editor.
  2. At the bottom of game.cs, add the following lines of code:
    function Sprite::onMouseDown(%this)
    {	
        dynamicmenuGui.addGuiControl(backgroundGui);
        backgroundGUI.addGuiControl(exitGui);
        Canvas.pushDialog(dynamicmenuGui);
    }
    
  3. Save game.cs.
  4. Load a level in TGB.
  5. Click the Create tab.
  6. Drag a static sprite onto your level.
  7. In the level, click on the sprite.
  8. Click the Edit tab.
  9. Expand Scripting.
  10. Mark the Use Mouse Events checkbox.
  11. In the Class field, enter Sprite.
  12. Press CTRL+S to save your level.
  13. Test your level. When you click on the sprite, your generated GUI appears on screen.