LogoLogo
  • Gum Tool
    • Introduction
    • Setup
      • Running from Source
    • Showcase
    • Tutorials and Examples
      • Intro Tutorials
        • 1 - The Basics
        • 2 - Variables Tab
        • 3 - Files
        • 4 - Components
        • 5 - Exposing Variables
        • 6 - Parent
        • 7 - States
        • 8 - State Categories
      • Animation Tutorials
        • 1 - Introduction to Animation
        • 2 - Creating an Animation
        • 3 - Playing Animations inside other Animations
        • 4 - Combining Multiple Categories
      • Examples
        • Bottom-Up Stack
        • Centering
        • Custom NineSlice
        • Health Bar
        • Padding
    • Gum Elements
      • General Properties
        • Alpha
        • Base Type (Inheritance)
        • Blend
        • Clips Children
        • Has Events
        • Height Units
        • Ignored By Parent Size
        • Locked
        • Max Height
        • Max Width
        • Min Height
        • Min Width
        • Order
        • Parent
        • Rotation
        • Visible
        • Variable References
        • Width Units
        • X
        • X Origin
        • X Units
        • Y
        • Y Origin
        • Y Units
      • Behaviors
        • Default Implementation
      • Circle
      • ColoredRectangle
      • Component
        • Default Child Container
      • Container
        • Children Layout
        • Contained Type
        • Is Render Target
        • Stack Spacing
        • Wraps Children
      • NineSlice
        • Blend
        • Custom Frame Texture Coordinate Width
        • Texture Address
        • Texture Left
        • Texture Top
      • Polygon
        • Points
      • Skia Standard Elements
        • General Properties
          • Has Dropshadow
          • Is Filled
          • Use Gradient
        • Arc
          • Start Angle
          • Sweep Angle
          • Thickness
        • Canvas
        • ColoredCircle
        • LottieAnimation
        • RoundedRectangle
          • Corner Radius
        • Svg
      • Sprite
        • Color
        • Source File
        • Texture Address
        • Wrap
      • States
        • Categories
      • Text
        • Blue
        • Color
        • Font
        • Font Scale
        • Font Size
        • Green
        • Is Bold
        • Is Italic
        • MaxLettersToShow
        • Outline Thickness
        • Red
        • Text
        • Text Overflow Horizontal Mode
        • Text Overflow Vertical Mode
        • Use Custom Font
        • Use Font Smoothing
    • Project Tab
    • Code Tab
      • Runtime Generation Details
      • Generation Scope
      • Inheritance Location
      • Is CodeGen Plugin Enabled
      • Show CodeGen Preview
    • Localization
    • Menu
      • Content
      • Project Properties
    • Plugins
      • AddAndRemoveVariablesForType
      • AddMenuItem
      • Export
      • Setting Up Post Build Events
    • Variables
      • Add Variable
    • Bitmap font generator (.fnt)
    • Upgrading
      • Migrating 2025 April 27 to Preview
      • Breaking Changes
        • Removal of Variable Spaces
  • Code
    • Gum Code Reference
      • AnimationRuntime
      • BitmapCharacterInfo
      • BitmapFont
      • Camera
      • CircleRuntime
      • ColoredRectangleRuntime
      • Component Runtimes
      • ContainerRuntime
      • Cursor
      • Gum Class Overview
      • DataUiGrid
        • Reflection
        • Categories
      • ElementSave
        • ToGraphicalUiElement
      • GraphicalUiElement
        • Absolute Values
        • AddToManagers
        • AnimateSelf
        • ApplyState
        • BlendState
        • CanvasHeight
        • CanvasWidth
        • Children
        • ContainedElements
        • Font Values
        • GetAbsoluteHeight
        • GetAbsoluteWidth
        • GetChildByNameRecursively
        • GetFrameworkElementByName
        • IsAllLayoutSuspended
        • Parent
        • RemoveFromManagers
        • UpdateLayout
      • GumProjectSave
      • IDataUi
      • InstanceMember
      • InstanceSave
      • InteractiveGue
        • CurrentInputReceiver
        • RaiseChildrenEventsOutsideOfBounds
        • RollOverBubbling
      • IPositionedSizedObject
      • Layer
      • NineSliceRuntime
      • RectangleRuntime
      • Renderer
        • SinglePixelTexture
      • SelectedState
      • SpriteRenderer
        • LastFrameDrawStates
      • SpriteRuntime
        • TextureAddress
        • TextureHeight
        • TextureLeft
        • TextureTop
        • TextureWidth
      • TextRuntime
        • Color
        • FontScale
        • FontSize
        • HorizontalAlignment
        • Text Wrapping
        • VerticalAlignment
      • VariableSave
    • FNA
    • Kni
    • Meadow
    • MonoGame
      • Setup
        • Linking Game Project to Source (Optional)
      • Tutorials
        • Gum Project Forms Tutorial
          • Setup
          • Gum Screens
          • Common Component Types
          • Styling
          • Multiple Screens
        • Code-Only Gum Forms Tutorial
          • Setup
          • Forms Controls
          • ListBox Items
          • Input in Forms
        • [Deprecated] Gum Project (.gumx) Tutorial
          • Setup
          • Gum Screens
          • Gum Forms
          • Customizing Forms
          • Strongly Typed Components Using Code Generation
          • Multiple Screens
      • Setup for GumBatch (Optional)
      • Loading a Gum Project (Optional)
      • async Programming
      • Custom Runtimes
      • GumBatch
      • Gum Forms
        • Binding (ViewModels)
        • Controls
          • Button
          • CheckBox
          • FrameworkElement
            • BindingContext
            • IsEnabled
            • IsFocused
            • ModalRoot and PopupRoot
            • SetBinding
          • ListBox
          • ListBoxItem
          • MenuItem
          • PasswordBox
          • RadioButton
          • ScrollViewer
            • VerticalScrollBarValue
          • StackPanel
          • Slider
          • TextBox
        • Control Customization In Code
          • MenuItem
        • Control Customization in Gum Tool
        • Gamepad Support
        • Keyboard Support
        • Troubleshooting
      • File Loading
      • Resizing the Game Window
      • Known Issues
      • Samples
        • MonoGameGumFormsSample
    • Nez
    • Silk.NET
    • SkiaGum
      • Setup
        • WPF
    • .NET MAUI
      • Setup
Powered by GitBook
On this page
  • Introduction
  • Code Example - Instantiating a Component
  • Adding a Component Runtime to a Parent
  • Adding to a Container
  • Adding to PopupRoot/ModalRoot
  • Adding to GumService Root
  • Troubleshooting Component Creation
  • SetProperty
  • Apply State

Was this helpful?

Edit on GitHub
Export as PDF
  1. Code
  2. Gum Code Reference

Component Runtimes

PreviousColoredRectangleRuntimeNextContainerRuntime

Last updated 2 months ago

Was this helpful?

Introduction

Components in a Gum project can be instantiated in custom code. Custom components can be created in code for a number of reasons:

  1. To create a variable number of items, such as items in an inventory component

  2. To create popups which may appear at any point in the app

Code Example - Instantiating a Component

Before instantiating a component from a Gum project, you must first have your Gum project loaded. For more information see the .

Once you have instantiated your project, you can create a component as shown in the following code:

// This assumes that your project has at least 1 component
var componentRuntime = ObjectFinder.Self.GumProjectSave.Components.First()
    .ToGraphicalUiElement();

// Add this component to the desired container

The Components property contains a list of all components, so you can also access components by name or other property. For example, the First method can be used to find a component by name as shown in the following code:

var componentSave = ObjectFinder.Self.GumProjectSave.Components
    .First(item => item.Name == "ColoredRectangleComponent");

var componentRuntime = componentSave.ToGraphicalUiElement();
// the componentRuntime can be modified here, and added to the desired container

Note that the name passed to the First method should match the name given in Gum. For example, in this case the code searches for a component named ColoredRectangleComponent.

If a component is in a folder, then use the qualified name relative to the Components folder. For example, the following component's name at runtime is "Buttons/StandardButton"

Adding a Component Runtime to a Parent

A newly-created component must be added directly or indirectly to managers. The following are the possible ways to add to managers:

Adding to a Container

The newly instantiated component can be added to a container in the screen. This container can be an actual ContainerRuntime instance, or to a control such as a ListBox.

// do not add to managers, since it will be added to a container
var newComponentRuntime = componentSave.ToGraphicalUiElement();
// assuming ScreenRoot is a valid root
var container = ScreenRoot.GetGraphicalUiElementByName("DesiredContainer");
container.Children.Add(newComponentRuntime);

To destroy the component, remove it from its parent, or set its parent to null:

newComponentRuntime.Parent = null;

Adding to PopupRoot/ModalRoot

The newly instantiated component can be added either the PopupRoot or ModalRoot. PopupRoot is used for popups which should appear on top of other controls, but which should not steal input. ModalRoot is used for popups which should steal focus from all other controls.

The following code shows how to create a Toast instance to display a message to a user. The code assumes your code has a valid Toast component.

// assumes toastComponent is a valid component
var newToastRuntime = toastComponent.ToGraphicalUiElement();
FrameworkElement.PopupRoot.Children.Add(newToastRuntime);
// the newToastRuntime needs to be removed from PopupRoot later

The following code shows how to create a MessageBox instance and add it to the ModalRoot so it receives exclusive input.

// assumes toastComponent is a valid component
var newMessageBoxRuntime = messageBoxComponent.ToGraphicalUiElement();
FrameworkElement.ModalRoot.Children.Add(newMessageBoxRuntime);
// the newMessageBoxRuntime needs to be removed from ModalRoot later

To destroy the component, remove it from its parent, or set its parent to null:

newMessageBoxRuntime.Parent = null;

Adding to GumService Root

Components can be added directly to the GumService Root. Usually items are only added directly to GumService Root in the following situations:

  • If they are a Screen, or will not be contained by any other object, such as if your project is not using screens.

  • For testing/debugging.

  • If your game has multiple roots, you can add instances to a list of GraphicalUiElements which are passed to Update. This is considered an advanced scenario.

var newComponentRuntime = componentSave.ToGraphicalUiElement();
newComponentRuntime.AddToRoot();

To destroy the component, call RemoveFromRoot:

newComponentRuntime.RemoveFromRoot();

Troubleshooting Component Creation

SetProperty

The SetProperty method can be used to set properties on components which are not natively part of GraphicalUiElement. This is useful in the following situations:

  • Setting a property which may not exist on all GraphicalUiElements, such as the Text property on a GraphicalUiElement for a Text standard element

  • Setting a property which has been exposed

If a GraphicalUiElement is a Text instance, the Text property can be assigned through SetProperty as shown in the following code:

myTextInstance.SetProperty("Text", "I'm set in code");

If a component has an exposed variable, then this variable can be assigned through SetProperty. For example, consider the following component which exposes its Text variable:

This can be assigned through the SetProperty. Be sure to use the name exactly as it appears in Gum:

myExposedVariableComponentInstance.SetProperty("Text", "I'm set in code");

Apply State

States can be applied in code by string (unqualified name), or by accessing the state on the backing ComponentSave. Note, this can also be performed on screens and standards.

 var setMeInCode = currentScreenElement.GetGraphicalUiElementByName("SetMeInCode");

 // States can be found in the Gum element's Categories and applied:
 var stateToSet = setMeInCode.ElementSave.Categories
     .FirstOrDefault(item => item.Name == "RightSideCategory")
     .States.Find(item => item.Name == "Blue");
 setMeInCode.ApplyState(stateToSet);

 // Alternatively states can be set in an "unqualified" way, which can be easier, but can 
 // result in unexpected behavior if there are multiple states with the same name:
 setMeInCode.ApplyState("Green");

 // states can be constructed dynamically too. This state makes the SetMeInCode instance bigger:
 var dynamicState = new StateSave();
 dynamicState.Variables.Add(new VariableSave()
 {
     Value = 300f,
     Name = "Width",
     Type = "float",
     // values can exist on a state but be "disabled"
     SetsValue = true
 });
 dynamicState.Variables.Add(new VariableSave()
 {
     Value = 250f,
     Name = "Height",
     Type = "float",
     SetsValue = true
 });
 setMeInCode.ApplyState(dynamicState);

If your component is not visible, this may be a file issue. By default Gum project loading will not throw exceptions on missing files, and it will attempt to re-create missing file components. For more information, see the .

Loading a Gum Project page
Troubleshooting section in the Loading .gumx page
ColoredRectangleComponent in Gum
StandardButton component in the Buttons folder in Gum
Component exposing a Text variable