### Build bGUI Project (Bash)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/getting-started.md
This bash command builds the bGUI project in Release mode. It assumes you have the .NET SDK installed and are in the root directory of the bGUI project.
```bash
dotnet build bGUI.sln -c Release
```
--------------------------------
### bGUI Fluent API Example (C#)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/getting-started.md
This C# snippet illustrates bGUI's fluent builder pattern for creating UI elements. It shows how to chain method calls to configure properties like text, size, theme, and event handlers before finalizing the element with `.Build()`.
```csharp
UI.Button(parent)
.SetText("Save") // Configure text
.SetSize(120, 30) // Set size
.Primary() // Apply theme
.OnClick(() => { })
.Build(); // Finalize and return wrapper
```
--------------------------------
### Utilize LayoutUtils for Canvas and Anchor Setup (C#)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/layouts.md
Presents helper methods from the `LayoutUtils` class for common UI setup tasks. This includes configuring a canvas scaler for specific resolutions and efficiently setting anchors for various parent-filling scenarios (fill parent, dock top/bottom/left/right). It also provides helpers for setting fixed or flexible dimensions on layout elements.
```csharp
using bGUI.Utilities;
// Setup canvas scaler
LayoutUtils.SetupCanvasScaler(canvas, 1920, 1080);
// Setup anchors
LayoutUtils.SetFillParent(rectTransform);
LayoutUtils.SetDockTop(rectTransform, height);
LayoutUtils.SetDockBottom(rectTransform, height);
LayoutUtils.SetDockLeft(rectTransform, width);
LayoutUtils.SetDockRight(rectTransform, width);
// Layout element helpers
LayoutUtils.SetFixedWidth(rectTransform, width);
LayoutUtils.SetFixedHeight(rectTransform, height);
LayoutUtils.SetFlexibleWidth(rectTransform, flex);
LayoutUtils.SetFlexibleHeight(rectTransform, flex);
```
--------------------------------
### Inventory Grid Example in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/layouts.md
An example of a grid layout configured for an inventory system, using a fixed column count. This sets up a grid with 4 columns and adds multiple inventory slots.
```csharp
var inventory = UI.Panel(parent)
.SetSize(350, 450)
.SetBackgroundColor(new Color(0.15f, 0.15f, 0.2f, 0.95f))
.SetRounded(12)
.WithGridLayout(layout => layout
.SetCellSize(70, 70)
.SetSpacing(5, 5)
.SetPadding(10)
.SetConstraint(GridLayoutGroup.Constraint.FixedColumnCount)
.SetConstraintCount(4)) // 4 columns
.Build();
// Add inventory slots
for (int i = 0; i < 20; i++)
{
var slot = UI.Panel(inventory.RectTransform)
.SetSize(70, 70)
.SetBackgroundColor(new Color(0.3f, 0.3f, 0.35f))
.SetRounded(4)
.Build();
}
```
--------------------------------
### Create Settings Menu UI in C# with BGUI
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/api-guide.md
This C# code snippet demonstrates the creation of a settings menu using the BGUI framework. It includes setting up a canvas, panels with layout options, text labels, a slider for volume, a toggle for fullscreen, a dropdown for difficulty, and buttons for apply/cancel actions. The example utilizes BGUI's fluent API for building UI components and handling user interactions.
```csharp
public class CompleteExample : MelonMod
{
private void CreateSettingsMenu()
{
// Create canvas
var canvas = UI.Canvas("SettingsMenu")
.SetRenderMode(RenderMode.ScreenSpaceOverlay)
.SetSortingOrder(100)
.SetReferenceResolution(1920, 1080)
.Build();
// Create main panel with vertical layout
var panel = UI.Panel(canvas.RectTransform)
.SetSize(450, 550)
.SetAnchor(0.5f, 0.5f)
.SetBackgroundColor(new Color(0.1f, 0.1f, 0.15f, 0.95f))
.SetRounded(12)
.WithVerticalLayout(layout => layout
.SetPadding(20)
.SetSpacing(15)
.SetChildAlignment(TextAnchor.UpperCenter))
.Build();
// Title
UI.Text(panel.RectTransform)
.SetContent("Settings")
.Title()
.SetSize(410, 40)
.Build();
// Volume slider
var volumeRow = CreateSettingRow(panel.RectTransform, "Volume");
UI.Slider(volumeRow.RectTransform)
.SetRange(0, 100)
.SetValue(75)
.SetWholeNumbers(true)
.SetHorizontal(200, 24)
.OnValueChanged(v => MelonLogger.Msg($"Volume: {v}"))
.Build();
// Fullscreen toggle
var fullscreenRow = CreateSettingRow(panel.RectTransform, "Fullscreen");
UI.Toggle(fullscreenRow.RectTransform)
.SetIsOn(true)
.OnValueChanged(on => MelonLogger.Msg($"Fullscreen: {on}"))
.Build();
// Difficulty dropdown
var difficultyRow = CreateSettingRow(panel.RectTransform, "Difficulty");
UI.Dropdown(difficultyRow.RectTransform)
.SetOptions(new[] { "Easy", "Normal", "Hard", "Extreme" })
.SetValue(1)
.SetSize(150, 30)
.OnValueChanged(idx => MelonLogger.Msg($"Difficulty: {idx}"))
.Build();
// Buttons row
var buttonRow = UI.Panel(panel.RectTransform)
.SetHeight(40)
.WithHorizontalLayout(layout => layout
.SetSpacing(15)
.SetChildAlignment(TextAnchor.MiddleCenter))
.Build();
UI.Button(buttonRow.RectTransform)
.SetText("Cancel")
.SetSize(100, 35)
.Secondary()
.OnClick(() => HideMenu())
.Build();
UI.Button(buttonRow.RectTransform)
.SetText("Apply")
.SetSize(100, 35)
.Success()
.OnClick(() => SaveSettings())
.Build();
}
private PanelWrapper CreateSettingRow(Transform parent, string label)
{
return UI.Panel(parent)
.SetHeight(40)
.WithHorizontalLayout(layout => layout
.SetSpacing(10)
.SetChildAlignment(TextAnchor.MiddleLeft))
.Build();
}
}
```
--------------------------------
### Use Quick Builders for Pre-styled Elements in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/theming.md
Demonstrates the use of `QuickBuilders` in C# for creating common pre-styled UI elements such as buttons, text labels, and cards with predefined themes.
```csharp
using bGUI.Core.Extensions;
// Pre-themed buttons
var save = QuickBuilders.PrimaryButton(parent, "Save");
var cancel = QuickBuilders.SecondaryButton(parent, "Cancel");
var confirm = QuickBuilders.SuccessButton(parent, "Confirm");
var delete = QuickBuilders.DangerButton(parent, "Delete");
// Text presets
var title = QuickBuilders.TitleText(parent, "Settings");
var heading = QuickBuilders.HeadingText(parent, "Section");
var label = QuickBuilders.Label(parent, "Username:");
var error = QuickBuilders.ErrorText(parent, "Invalid input");
var success = QuickBuilders.SuccessText(parent, "Saved!");
// Panel presets
var card = QuickBuilders.Card(parent); // Light rounded card
var darkCard = QuickBuilders.DarkCard(parent); // Dark rounded card
```
--------------------------------
### Use QuickBuilders for Common Layout Containers (C#)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/layouts.md
Introduces QuickBuilders for rapidly creating common layout patterns like horizontal and vertical containers. These builders simplify the setup of containers that fill their parent with default spacing and padding. Requires the `bGUI.Core.Extensions` namespace.
```csharp
using bGUI.Core.Extensions;
// Horizontal container
var hBox = QuickBuilders.HorizontalContainer(parent);
// - Fills parent
// - Small spacing
// - Medium padding
// Vertical container
var vBox = QuickBuilders.VerticalContainer(parent);
// - Fills parent
// - Small spacing
// - Medium padding
```
--------------------------------
### Configure bGUI Project References (XML)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/getting-started.md
This XML snippet shows how to update the DLL references in your bGUI project's .csproj file. Ensure the 'HintPath' points to the correct location of MelonLoader.dll within your game's installation directory.
```xml
D:\\SteamLibrary\\steamapps\\common\\YourGame\\MelonLoader\\net35\\MelonLoader.dll
```
--------------------------------
### Complete bGUI Object Pooling Example (Dynamic List)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/pooling.md
This C# example demonstrates a complete implementation of a dynamic list using bGUI's object pooling system. It shows how to enable pooling, create UI elements like canvases, panels, and buttons, add items to the list using pooled elements, and efficiently remove items by returning them to the pool. This showcases the practical application of pooling for performance optimization.
```csharp
using System.Collections.Generic;
using UnityEngine;
public class DynamicList : MelonMod
{
private CanvasWrapper _canvas;
private PanelWrapper _listContainer;
private List _items = new List();
public override void OnInitializeMelon()
{
UI.EnablePooling(); // Enable pooling globally
CreateUI();
}
private void CreateUI()
{
_canvas = UI.Canvas("ListCanvas")
.SetRenderMode(RenderMode.ScreenSpaceOverlay)
.SetSortingOrder(100)
.Build();
_listContainer = UI.Panel(_canvas.RectTransform)
.SetSize(400, 600)
.SetAnchor(0.5f, 0.5f)
.WithVerticalLayout(v => v
.SetPadding(10)
.SetSpacing(5))
.Build();
}
// Add item using pooled elements
private void AddItem(string text)
{
var item = UI.Panel(_listContainer.RectTransform)
.SetHeight(50)
.SetBackgroundColor(Theme.Dark)
.WithHorizontalLayout(h => h
.SetPadding(10, 0)
.SetSpacing(10))
.Build();
UI.Text(item.RectTransform)
.SetContent(text)
.SetAlignment(TextAnchor.MiddleLeft)
.Build();
UI.Button(item.RectTransform)
.SetText("X")
.Small()
.Error()
.OnClick(() => RemoveItem(item))
.Build();
_items.Add(item);
}
// Return to pool instead of destroying
private void RemoveItem(PanelWrapper item)
{
_items.Remove(item);
UI.ReturnToPool(item); // Recycled for reuse
}
// Clear all items efficiently
private void ClearAllItems()
{
foreach (var item in _items)
{
UI.ReturnToPool(item);
}
_items.Clear();
}
}
```
--------------------------------
### Create a Basic Mod Menu with bGUI (C#)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/getting-started.md
This C# code demonstrates how to create a simple mod menu using bGUI. It includes setting up MelonLoader information, handling input to toggle menu visibility, and building a UI with a canvas, panel, text, and button using bGUI's fluent API.
```csharp
using MelonLoader;
using UnityEngine;
using bGUI;
using bGUI.Components;
[assembly: MelonInfo(typeof(MyMod), "MyMod", "1.0.0", "YourName")]
[assembly: MelonGame("GameDev", "YourGame")]
namespace MyMod
{
public class MyMod : MelonMod
{
private CanvasWrapper? _canvas;
private PanelWrapper? _menuPanel;
private bool _isMenuVisible = false;
public override void OnInitializeMelon()
{
MelonLogger.Msg("MyMod initialized! Press F1 to toggle menu.");
}
public override void OnUpdate()
{
// Toggle menu with F1
if (Input.GetKeyDown(KeyCode.F1))
{
_isMenuVisible = !_isMenuVisible;
if (_isMenuVisible)
{
if (_canvas == null) CreateUI();
_menuPanel?.GameObject.SetActive(true);
}
else
{
_menuPanel?.GameObject.SetActive(false);
}
}
}
private void CreateUI()
{
// Create a canvas for our UI
_canvas = UI.Canvas("MyModCanvas")
.SetRenderMode(RenderMode.ScreenSpaceOverlay)
.SetSortingOrder(100) // Render on top
.SetReferenceResolution(1920, 1080)
.Build();
// Create a centered panel
_menuPanel = UI.Panel(_canvas.RectTransform)
.SetSize(400, 300)
.SetAnchor(0.5f, 0.5f) // Center anchor
.SetBackgroundColor(new Color(0.1f, 0.1f, 0.15f, 0.95f))
.SetRounded(12) // Rounded corners
.Build();
// Add a title
UI.Text(_menuPanel.RectTransform)
.SetContent("My Mod Menu")
.SetFontSize(18)
.SetColor(Color.white)
.SetSize(370, 30)
.Build();
// Add a button
UI.Button(_menuPanel.RectTransform)
.SetText("Click Me!")
.SetSize(150, 35)
.Primary() // Use primary color theme
.OnClick(() => MelonLogger.Msg("Button clicked!"))
.Build();
}
}
}
```
--------------------------------
### bGUI Slider Configuration Examples
Source: https://github.com/ifbars/bgui/blob/master/README.md
Demonstrates how to create and configure sliders in bGUI, including setting value ranges, initial values, number formatting, and custom color schemes for fill, background, and handle.
```csharp
// Basic slider
UI.Slider(parent)
.SetRange(0, 100)
.SetValue(50)
.SetWholeNumbers(true)
.SetSize(200, 20)
.OnValueChanged(val => MelonLogger.Msg($"Value: {val}"))
.Build();
// Percentage slider with color scheme
UI.Slider(parent)
.SetAsPercentage(75)
.SetHorizontal(250, 24)
.SetColorScheme(
fillColor: new Color(0.2f, 0.8f, 0.2f),
backgroundColor: new Color(0.2f, 0.2f, 0.2f),
handleColor: Color.white)
.Build();
```
--------------------------------
### Minimal Unity Menu Toggle Example with bGUI
Source: https://github.com/ifbars/bgui/blob/master/README.md
A C# example demonstrating how to create and toggle a simple UI menu in Unity using bGUI. It utilizes MelonLoader's OnUpdate for input handling and bGUI's builder API to construct a canvas, panel, text, and button.
```csharp
using MelonLoader;
using UnityEngine;
using bGUI;
using bGUI.Components;
public class MyMod : MelonMod
{
private CanvasWrapper? _canvas;
private PanelWrapper? _panel;
private bool _visible;
public override void OnUpdate()
{
if (!Input.GetKeyDown(KeyCode.F1)) return;
_visible = !_visible;
if (_visible)
{
if (_canvas == null) CreateUI();
_panel?.GameObject.SetActive(true);
}
else
{
_panel?.GameObject.SetActive(false);
}
}
private void CreateUI()
{
_canvas = UI.Canvas("MyModCanvas")
.SetRenderMode(RenderMode.ScreenSpaceOverlay)
.SetSortingOrder(100)
.SetReferenceResolution(1920, 1080)
.Build();
_panel = UI.Panel(_canvas.RectTransform)
.SetSize(400, 300)
.SetAnchor(0.5f, 0.5f)
.SetBackgroundColor(new Color(0.1f, 0.1f, 0.15f, 0.95f))
.SetRounded(12)
.WithVerticalLayout(layout => layout
.SetPadding(15)
.SetSpacing(10)
.SetChildAlignment(TextAnchor.UpperCenter))
.Build();
UI.Text(_panel.RectTransform)
.SetContent("My Mod Menu")
.SetFontSize(18)
.SetColor(Color.white)
.SetSize(370, 30)
.Build();
UI.Button(_panel.RectTransform)
.SetText("Click Me")
.SetSize(200, 35)
.Primary()
.OnClick(() => MelonLogger.Msg("Button clicked!"))
.Build();
}
}
```
--------------------------------
### Basic Grid Layout in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/layouts.md
Demonstrates a basic grid layout with fixed cell sizes, spacing, and padding. This example creates a 3x3 grid of colored panels.
```csharp
var grid = UI.Panel(parent)
.SetSize(400, 400)
.SetBackgroundColor(Theme.Dark)
.WithGridLayout(layout => layout
.SetCellSize(90, 90) // Size of each cell
.SetSpacing(10, 10) // Horizontal and vertical spacing
.SetPadding(15) // Padding around grid
.SetStartCorner(GridLayoutGroup.Corner.UpperLeft)
.SetStartAxis(GridLayoutGroup.Axis.Horizontal)
.SetChildAlignment(TextAnchor.MiddleCenter))
.Build();
// Add items to the grid
for (int i = 0; i < 9; i++)
{
UI.Panel(grid.RectTransform)
.SetSize(80, 80)
.SetBackgroundColor(Theme.Secondary)
.SetRounded(8)
.Build();
}
```
--------------------------------
### Apply Button Size Presets in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/theming.md
Shows how to apply predefined size presets to buttons using extension methods in C#. It also demonstrates setting button sizes manually using theme constants.
```csharp
// Using theme size constants
UI.Button(parent).SetText("Small").Small().Build();
UI.Button(parent).SetText("Default").DefaultSize().Build();
UI.Button(parent).SetText("Large").Large().Build();
// Or set manually
UI.Button(parent)
.SetSize(Theme.Size.Button) // 120x30
.SetSize(Theme.Size.LargeButton) // 160x40
.SetSize(Theme.Size.SmallButton) // 80x25
.Build();
```
--------------------------------
### Apply Text Size Presets in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/theming.md
Illustrates how to apply predefined text size presets to text elements using extension methods in C#. This allows for quick styling of text with different font sizes.
```csharp
UI.Text(parent).SetContent("Title").Title().Build(); // 32pt
UI.Text(parent).SetContent("Heading").Heading().Build(); // 24pt
UI.Text(parent).SetContent("Body").Large().Build(); // 18pt
UI.Text(parent).SetContent("Caption").Small().Build(); // 10pt
```
--------------------------------
### Manage UI Animation Lifecycle in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/animations.md
Demonstrates how to initialize, enable, and disable UI animations within a C# class. It includes creating animation instances, adding them to a list, starting them on UI creation, and cleaning them up when the UI is destroyed to prevent memory leaks.
```csharp
public class MenuWithAnimations
{
private List _animations = new List();
private void CreateUI()
{
// Create animations
var pulse = new PulseAnimation(title, 0.95f, 1.05f, 2f);
var fade = new FadeAnimation(subtitle, 0.5f, 1f, 1.5f);
_animations.Add(pulse);
_animations.Add(fade);
// Start all animations
foreach (var anim in _animations)
{
anim.SetEnabled(true);
}
}
private void OnDestroy()
{
// Clean up animations
foreach (var anim in _animations)
{
anim.SetEnabled(false);
}
_animations.Clear();
}
}
```
--------------------------------
### Apply Semantic Panel Themes in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/theming.md
Illustrates how to apply semantic color themes to panels using extension methods in C#. This enables easy background color customization for panels.
```csharp
UI.Panel(parent)
.SetSize(200, 100)
.Primary() // Background = primary color
.Build();
UI.Panel(parent)
.Dark() // Dark background
.Build();
UI.Panel(parent)
.Light() // Light background
.Build();
```
--------------------------------
### Generate API Documentation with DocFX
Source: https://github.com/ifbars/bgui/blob/master/README.md
Provides instructions on how to generate API documentation for the project using DocFX. This involves installing the DocFX tool globally via the .NET CLI and then running the documentation generation process.
```bash
# Install docfx (one-time)
dotnet tool install -g docfx
```
--------------------------------
### Builder Styling Shortcuts (C#)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/api-guide.md
Provides extension methods for chaining theme and size configurations for buttons, text, and panels. These methods simplify common styling tasks by offering a fluent API.
```csharp
// Button themes
buttonBuilder.Primary()
buttonBuilder.Secondary()
buttonBuilder.Success()
buttonBuilder.Warning()
buttonBuilder.Error()
buttonBuilder.Info()
buttonBuilder.Light()
buttonBuilder.Dark()
// Button sizes
buttonBuilder.Small()
buttonBuilder.DefaultSize()
buttonBuilder.Large()
// Text themes
textBuilder.Primary()
textBuilder.Success()
textBuilder.Title()
textBuilder.Heading()
textBuilder.Large()
textBuilder.Small()
// Panel themes
panelBuilder.Primary()
panelBuilder.Secondary()
panelBuilder.Dark()
panelBuilder.Light()
// Common styling
builder.Rounded(radius)
builder.RoundedSmall()
builder.RoundedLarge()
builder.Circle()
```
--------------------------------
### Access Built-in Colors in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/theming.md
Demonstrates how to access predefined semantic color tokens directly from the Theme class in C#. These colors can be applied to various UI elements.
```csharp
using bGUI.Core.Constants;
Color primary = Theme.Primary; // Blue
Color success = Theme.Success; // Green
Color warning = Theme.Warning; // Yellow
Color error = Theme.Error; // Red
Color info = Theme.Info; // Cyan
Color light = Theme.Light; // Light gray
Color dark = Theme.Dark; // Dark gray
```
--------------------------------
### Apply Semantic Text Themes in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/theming.md
Demonstrates applying semantic color themes to text elements using extension methods in C#. This provides a straightforward way to style text with predefined colors.
```csharp
UI.Text(parent)
.SetContent("Primary text")
.Primary() // Primary color
.Build();
UI.Text(parent)
.SetContent("Error message")
.Error() // Error color
.Build();
```
--------------------------------
### Quick UI Builders (C#)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/api-guide.md
Offers pre-styled factory methods for quickly creating common UI elements like buttons, text, and panels. These methods simplify instantiation and initial configuration, reducing boilerplate code.
```csharp
// Buttons
QuickBuilders.PrimaryButton(parent, text)
QuickBuilders.SecondaryButton(parent, text)
QuickBuilders.SuccessButton(parent, text)
QuickBuilders.DangerButton(parent, text)
// Text
QuickBuilders.TitleText(parent, text)
QuickBuilders.HeadingText(parent, text)
QuickBuilders.Label(parent, text)
QuickBuilders.ErrorText(parent, text)
QuickBuilders.SuccessText(parent, text)
// Panels
QuickBuilders.Card(parent)
QuickBuilders.DarkCard(parent)
QuickBuilders.Container(parent)
QuickBuilders.HorizontalContainer(parent)
QuickBuilders.VerticalContainer(parent)
```
--------------------------------
### Apply Semantic Button Themes in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/theming.md
Shows how to apply semantic color themes to buttons using extension methods in C#. This allows for quick styling of buttons with predefined color schemes.
```csharp
// Semantic themes
UI.Button(parent).SetText("Save").Primary().Build();
UI.Button(parent).SetText("OK").Success().Build();
UI.Button(parent).SetText("Warning").Warning().Build();
UI.Button(parent).SetText("Delete").Error().Build();
UI.Button(parent).SetText("Info").Info().Build();
UI.Button(parent).SetText("Cancel").Secondary().Build();
UI.Button(parent).SetText("Menu").Light().Build();
UI.Button(parent).SetText("Dark").Dark().Build();
```
--------------------------------
### Create UI Text Elements with C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/api-guide.md
Builds UI text elements with configurable content, font size, color, and alignment. Offers theme extensions for quick styling of text elements.
```csharp
UI.Text(parent)
.SetContent(string)
.SetFontSize(int)
.SetColor(Color)
.SetAlignment(TextAnchor)
.SetSize(width, height)
// Theme extensions
.Primary()
.Secondary()
.Success()
.Warning()
.Error()
.Title()
.Heading()
.Large()
.Small()
.Build()
```
--------------------------------
### Apply Rounded Corners to UI Elements in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/theming.md
Demonstrates how to create UI elements with rounded corners using preset radii or by specifying a custom radius in C#. It also shows how to make elements circular.
```csharp
// Use preset radii
UI.Button(parent).RoundedSmall().Build(); // 4px radius
UI.Button(parent).RoundedLarge().Build(); // 12px radius
// Or specify custom radius
UI.Panel(parent)
.SetRounded(8) // 8px radius
.Build();
// Make it circular (for square elements)
UI.Button(parent)
.SetSize(50, 50)
.Circle() // Large radius for circular shape
.Build();
```
--------------------------------
### Menu Open Animation using Coroutines in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/animations.md
Demonstrates animating a menu panel to open by fading in and scaling up using coroutines. This involves manipulating alpha and local scale over a specified duration.
```csharp
public class MyMod : MelonMod
{
private PanelWrapper _menuPanel;
private CanvasGroup _menuCanvasGroup;
private void CreateUI()
{
// Create menu
_menuPanel = UI.Panel(_canvas.RectTransform)
.SetSize(400, 500)
.SetAlpha(0) // Start invisible
.SetScale(0.9f, 0.9f) // Start slightly smaller
.Build();
_menuCanvasGroup = _menuPanel.GameObject.GetComponent();
if (_menuCanvasGroup == null)
_menuCanvasGroup = _menuPanel.GameObject.AddComponent();
// Start open animation
MelonCoroutines.Start(AnimateMenuOpen());
}
private IEnumerator AnimateMenuOpen()
{
float duration = 0.3f;
float elapsed = 0f;
_menuPanel.GameObject.SetActive(true);
while (elapsed < duration)
{
elapsed += Time.deltaTime;
float t = elapsed / duration;
// Fade in
_menuCanvasGroup.alpha = Mathf.Lerp(0, 1, t);
// Scale up
float scale = Mathf.Lerp(0.9f, 1f, t);
_menuPanel.RectTransform.localScale = new Vector3(scale, scale, 1);
yield return null;
}
_menuCanvasGroup.alpha = 1;
_menuPanel.RectTransform.localScale = Vector3.one;
}
}
```
--------------------------------
### Build UI Toggles with C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/api-guide.md
Constructs UI toggles with on/off states, labels, and customizable appearance. Allows setting interactability, colors, background images, and checkmark sprites. Includes event handling for value changes.
```csharp
UI.Toggle(parent)
.SetIsOn(bool)
.SetLabel(string)
.OnValueChanged(Action)
.SetInteractable(bool)
.SetColors(normal, highlighted, pressed, disabled)
.SetBackgroundImage(Sprite)
.SetCheckmarkImage(Sprite)
.SetLabelColor(Color)
.SetSize(width, height)
.SetPosition(x, y)
.SetAnchor(anchorX, anchorY)
.SetPivot(pivotX, pivotY)
.Build()
```
--------------------------------
### Horizontal Button Bar Example in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/layouts.md
A practical example of a horizontal layout used to create a button bar. This layout spans the parent's width and arranges buttons with specific padding and spacing.
```csharp
var buttonBar = UI.Panel(parent)
.FillParentWidth()
.SetHeight(50)
.SetBackgroundColor(Theme.Primary)
.WithHorizontalLayout(layout => layout
.SetPadding(10, 0)
.SetSpacing(15)
.SetChildAlignment(TextAnchor.MiddleLeft))
.Build();
UI.Button(buttonBar.RectTransform)
.SetText("New")
.Light()
.Small()
.Build();
UI.Button(buttonBar.RectTransform)
.SetText("Open")
.Light()
.Small()
.Build();
```
--------------------------------
### Utilize Quick Builders for UI Elements in C#
Source: https://github.com/ifbars/bgui/blob/master/README.md
Shows how to use pre-styled factory methods provided by `QuickBuilders` for common UI elements like buttons, text, and layout containers. This simplifies the creation of consistently themed UI components, reducing boilerplate code. Requires importing `bGUI.Core.Extensions`.
```csharp
using bGUI.Core.Extensions;
// Pre-themed buttons
var save = QuickBuilders.PrimaryButton(parent, "Save");
var cancel = QuickBuilders.SecondaryButton(parent, "Cancel");
var delete = QuickBuilders.DangerButton(parent, "Delete");
// Text presets
var title = QuickBuilders.TitleText(parent, "Settings");
var label = QuickBuilders.Label(parent, "Username:");
var error = QuickBuilders.ErrorText(parent, "Invalid input");
// Layout containers
var card = QuickBuilders.Card(parent);
var hBox = QuickBuilders.HorizontalContainer(parent);
var vBox = QuickBuilders.VerticalContainer(parent);
```
--------------------------------
### Implement Custom Color Shift Animation in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/animations.md
Provides an example of creating a custom animation by inheriting from `BaseAnimation` in C#. This `ColorShiftAnimation` cycles through an array of colors for an `Image` component, allowing for custom visual effects.
```csharp
using bGUI.Components.Animations;
public class ColorShiftAnimation : BaseAnimation
{
private readonly Color[] _colors;
private readonly float _speed;
private Image _image;
private int _currentIndex;
private float _timer;
public ColorShiftAnimation(IUIElement element, Color[] colors, float speed) : base(element)
{
_colors = colors;
_speed = speed;
_image = element.GameObject.GetComponent();
}
public override void Update()
{
if (!IsEnabled || _image == null) return;
_timer += Time.deltaTime;
if (_timer >= 1f / _speed)
{
_timer = 0f;
_currentIndex = (_currentIndex + 1) % _colors.Length;
_image.color = _colors[_currentIndex];
}
}
public override void Reset()
{
_timer = 0f;
_currentIndex = 0;
if (_image != null)
_image.color = _colors[0];
}
}
// Usage
var colorAnim = new ColorShiftAnimation(
element: panel,
colors: new[] { Color.red, Color.green, Color.blue },
speed: 1f
);
colorAnim.SetEnabled(true);
```
--------------------------------
### Vertical Layout with Child Size Control in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/layouts.md
Shows how to configure a vertical layout to control the width and height of child elements. This example sets children to expand to fill the panel's width but not force their height.
```csharp
var panel = UI.Panel(parent)
.SetSize(300, 400)
.WithVerticalLayout(layout => layout
.SetChildControlWidth(true) // Children expand to fill width
.SetChildControlHeight(false) // Don't force height
.SetChildForceExpandWidth(true)
.SetPadding(10)
.SetSpacing(10))
.Build();
```
--------------------------------
### bGUI Button Styling Examples
Source: https://github.com/ifbars/bgui/blob/master/README.md
Illustrates various ways to style buttons in bGUI using semantic color themes (Primary, Success, Warning, Error), size presets (Small, Default, Large), and custom colors with rounded corners.
```csharp
// Semantic color themes
UI.Button(parent).SetText("Save").Primary().Build();
UI.Button(parent).SetText("OK").Success().Build();
UI.Button(parent).SetText("Caution").Warning().Build();
UI.Button(parent).SetText("Delete").Error().Build();
// Size presets
UI.Button(parent).SetText("Small").Small().Build();
UI.Button(parent).SetText("Default").DefaultSize().Build();
UI.Button(parent).SetText("Large").Large().Build();
// Custom colors and rounded corners
UI.Button(parent)
.SetText("Custom")
.SetBackgroundColor(new Color(0.5f, 0.0f, 0.8f))
.SetRounded(8)
.SetSize(180, 40)
.OnClick(() => { /* handler */ })
.Build();
```
--------------------------------
### Apply Layout Properties for UI Element Arrangement (C#)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/layouts.md
Details common layout properties available for all layout types, including padding, spacing, and child alignment. It also specifies properties unique to horizontal/vertical layouts (child control and expansion) and grid layouts (cell size, start corner/axis, and constraints). These properties allow fine-grained control over how UI elements are positioned and sized within their containers.
```csharp
// Common Properties (all layouts)
// SetPadding(padding)
// SetPadding(left, right, top, bottom)
// SetSpacing(spacing)
// SetSpacing(x, y)
// SetChildAlignment(alignment)
// Horizontal/Vertical Specific
// SetChildControlWidth(bool)
// SetChildControlHeight(bool)
// SetChildForceExpandWidth(bool)
// SetChildForceExpandHeight(bool)
// Grid Specific
// SetCellSize(width, height)
// SetStartCorner(corner)
// SetStartAxis(axis)
// SetConstraint(constraint)
// SetConstraintCount(count)
```
--------------------------------
### Use QuickBuilders for Pre-Styled Elements in C#
Source: https://context7.com/ifbars/bgui/llms.txt
Demonstrates using QuickBuilders to create commonly used UI elements with consistent, pre-defined styling, such as buttons, text elements, and layout containers. Requires bGUI.Core.Extensions and UnityEngine.
```csharp
using bGUI.Core.Extensions;
using UnityEngine;
// Pre-themed buttons
ButtonWrapper saveBtn = QuickBuilders.PrimaryButton(parent, "Save");
ButtonWrapper cancelBtn = QuickBuilders.SecondaryButton(parent, "Cancel");
ButtonWrapper confirmBtn = QuickBuilders.SuccessButton(parent, "Confirm");
ButtonWrapper deleteBtn = QuickBuilders.DangerButton(parent, "Delete");
// Pre-styled text
TextWrapper title = QuickBuilders.TitleText(parent, "Settings");
TextWrapper heading = QuickBuilders.HeadingText(parent, "Audio");
TextWrapper label = QuickBuilders.Label(parent, "Username:");
TextWrapper error = QuickBuilders.ErrorText(parent, "Invalid input");
TextWrapper success = QuickBuilders.SuccessText(parent, "Saved!");
// Layout containers with preset styling
PanelWrapper card = QuickBuilders.Card(parent); // Light rounded card
PanelWrapper darkCard = QuickBuilders.DarkCard(parent); // Dark rounded card
PanelWrapper container = QuickBuilders.Container(parent); // Basic container
PanelWrapper hBox = QuickBuilders.HorizontalContainer(parent);
PanelWrapper vBox = QuickBuilders.VerticalContainer(parent);
```
--------------------------------
### Managing Animations in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/animations.md
Provides methods to control active animations, including disabling them to stop the effect and resetting them to their initial state.
```csharp
// Disable an animation
fadeAnim.SetEnabled(false);
// Reset to initial state
fadeAnim.Reset();
```
--------------------------------
### Basic Rotate Animation in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/animations.md
Implements continuous rotation for a UI element. It requires the target element and a speed value in degrees per second.
```csharp
// Create rotate animation
var rotateAnim = new RotateAnimation(
element: icon,
speed: 180f // Degrees per second
);
rotateAnim.SetEnabled(true);
```
--------------------------------
### Basic Move Animation in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/animations.md
Creates a wave-like vertical movement for a UI element. It requires the target element, an amplitude for the movement distance, and a speed value.
```csharp
// Create move animation
var moveAnim = new MoveAnimation(
element: panel,
amplitude: 10f, // Pixels to move up/down
speed: 3f // Speed of movement
);
moveAnim.SetEnabled(true);
```
--------------------------------
### Create Toggles and Dropdowns in C#
Source: https://github.com/ifbars/bgui/blob/master/README.md
Demonstrates how to create interactive UI elements like toggles and dropdowns using the bGUI framework. These elements can be configured with labels, options, sizes, and event handlers for value changes. The `Build()` method finalizes the element creation.
```csharp
// Toggle
UI.Toggle(parent)
.SetLabel("Enable Feature")
.SetIsOn(true)
.SetSize(200, 25)
.OnValueChanged(isOn => MelonLogger.Msg($"Toggled: {isOn}"))
.Build();
// Dropdown
UI.Dropdown(parent)
.SetOptions(new[] { "Low", "Medium", "High", "Ultra" })
.SetValue(1)
.SetSize(180, 30)
.OnValueChanged(idx => MelonLogger.Msg($"Selected: {idx}"))
.Build();
```
--------------------------------
### Set Custom Button Background Color in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/theming.md
Explains how to set a custom background color for a button in C# by creating a `Color` object and using the `SetBackgroundColor` method.
```csharp
var customColor = new Color(0.6f, 0.2f, 0.8f); // Purple
UI.Button(parent)
.SetBackgroundColor(customColor)
.Build();
```
--------------------------------
### Clear UI Pools
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/pooling.md
Provides methods to clear all pooled UI elements or specific types of pooled elements. This is usually not necessary but can be useful in certain scenarios.
```csharp
// Clear all pools
UIFactory.Instance.ClearAllPools();
// Or clear specific type
UIFactory.Instance.ClearPool();
```
--------------------------------
### Sequence Animation in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/animations.md
Highlights multiple UI elements in a sequential manner. It takes a list of elements, active and inactive colors, highlight duration, and a loop option.
```csharp
// Create a sequence
var sequence = new SequenceAnimation(
elements: new List { panel1, panel2, panel3, panel4 },
activeColor: new Color(0.3f, 0.6f, 1f),
inactiveColor: Theme.Dark,
highlightDuration: 0.5f,
loop: true
);
sequence.SetEnabled(true);
```
--------------------------------
### Create Buttons with bGUI
Source: https://context7.com/ifbars/bgui/llms.txt
Illustrates the creation of buttons using bGUI, showcasing text, size, position, anchor, and click handlers. It also covers applying semantic color themes (Primary, Success, Warning, Error, Info, Secondary) and size presets (Small, Default, Large). Custom styling with background color, specific colors for different states, and rounded corners is also demonstrated.
```csharp
using bGUI;
using bGUI.Components;
using UnityEngine;
// Basic button with click handler
ButtonWrapper button = UI.Button(parent)
.SetText("Click Me")
.SetSize(150, 35)
.SetPosition(0, 0)
.SetAnchor(0.5f, 0.5f)
.OnClick(() => MelonLogger.Msg("Button clicked!"))
.Build();
// Semantic color themes
UI.Button(parent).SetText("Save").Primary().Build(); // Blue
UI.Button(parent).SetText("OK").Success().Build(); // Green
UI.Button(parent).SetText("Caution").Warning().Build(); // Yellow
UI.Button(parent).SetText("Delete").Error().Build(); // Red
UI.Button(parent).SetText("Info").Info().Build(); // Cyan
UI.Button(parent).SetText("Cancel").Secondary().Build(); // Gray
// Size presets
UI.Button(parent).SetText("Small").Small().Build(); // 80x25
UI.Button(parent).SetText("Default").DefaultSize().Build(); // 120x30
UI.Button(parent).SetText("Large").Large().Build(); // 160x40
// Custom styling with rounded corners
UI.Button(parent)
.SetText("Custom")
.SetBackgroundColor(new Color(0.5f, 0.0f, 0.8f))
.SetColors(
normal: new Color(0.5f, 0.0f, 0.8f),
highlighted: new Color(0.6f, 0.1f, 0.9f),
pressed: new Color(0.4f, 0.0f, 0.7f),
disabled: new Color(0.3f, 0.3f, 0.3f, 0.5f))
.SetRounded(8)
.SetSize(180, 40)
.OnClick(() => { /* handler */ })
.Build();
```
--------------------------------
### Disable UI Pooling When Not Needed
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/pooling.md
Disables the UI pooling system to avoid overhead when pooling is not required, typically for static UI elements. This is often called during initialization.
```csharp
public override void OnInitializeMelon()
{
// Static UI - don't pool
UI.DisablePooling();
}
```
--------------------------------
### Basic Horizontal Layout in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/layouts.md
Illustrates a basic horizontal layout for a panel, arranging child elements from left to right. It includes settings for padding, spacing, and child alignment.
```csharp
var panel = UI.Panel(parent)
.SetSize(400, 60)
.SetBackgroundColor(Theme.Dark)
.WithHorizontalLayout(layout => layout
.SetPadding(10)
.SetSpacing(10)
.SetChildAlignment(TextAnchor.MiddleCenter))
.Build();
// Children are arranged horizontally
UI.Button(panel.RectTransform).SetText("Save").Build();
UI.Button(panel.RectTransform).SetText("Load").Build();
UI.Button(panel.RectTransform).SetText("Exit").Build();
```
--------------------------------
### Create Nested UI Panels with Different Layouts (C#)
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/layouts.md
Demonstrates how to build a complex UI by nesting panels with vertical and horizontal layouts. It includes creating a main container, title bar, content area, and bottom bar, each with specific layout configurations and child elements like text and buttons. This approach allows for modular and organized UI design.
```csharp
using UnityEngine;
using bGUI.Core;
// Main container with vertical layout
var mainPanel = UI.Panel(parent)
.SetSize(500, 600)
.WithVerticalLayout(v => v
.SetPadding(15)
.SetSpacing(10))
.Build();
// Title bar with horizontal layout
var titleBar = UI.Panel(mainPanel.RectTransform)
.SetHeight(40)
.WithHorizontalLayout(h => h
.SetPadding(10, 0)
.SetSpacing(10))
.Build();
UI.Text(titleBar.RectTransform)
.SetContent("Settings")
.Heading()
.Build();
UI.Button(titleBar.RectTransform)
.SetText("X")
.Small()
.OnClick(CloseMenu)
.Build();
// Content area with vertical layout
var content = UI.Panel(mainPanel.RectTransform)
.SetFlexibleHeight(1) // Fill remaining space
.WithVerticalLayout(v => v
.SetSpacing(15)
.SetPadding(10))
.Build();
// Add settings rows
AddSettingRow(content.RectTransform, "Volume", CreateSlider);
AddSettingRow(content.RectTransform, "Brightness", CreateSlider);
AddSettingRow(content.RectTransform, "Fullscreen", CreateToggle);
// Bottom bar with horizontal layout
var bottomBar = UI.Panel(mainPanel.RectTransform)
.SetHeight(50)
.WithHorizontalLayout(h => h
.SetPadding(10)
.SetSpacing(10)
.SetChildAlignment(TextAnchor.MiddleRight))
.Build();
UI.Button(bottomBar.RectTransform)
.SetText("Cancel")
.Secondary()
.Build();
UI.Button(bottomBar.RectTransform)
.SetText("Apply")
.Primary()
.Build();
```
--------------------------------
### Basic Pulse Animation in C#
Source: https://github.com/ifbars/bgui/blob/master/docs/articles/animations.md
Applies a scaling effect to a UI element, making it grow and shrink. It requires the target element, minimum and maximum scale values, and a speed parameter.
```csharp
// Create pulse animation
var pulseAnim = new PulseAnimation(
element: button,
minScale: 0.9f, // Minimum scale
maxScale: 1.1f, // Maximum scale
speed: 4f // Speed of pulsing
);
pulseAnim.SetEnabled(true);
```
--------------------------------
### Create Panels with Layouts in C#
Source: https://github.com/ifbars/bgui/blob/master/README.md
Illustrates the creation of UI panels with different layout managers, including vertical and grid layouts. Panels can be styled with background colors and rounded corners. Layout configurations define padding, spacing, and child alignment for organized UI elements.
```csharp
// Vertical layout panel
var container = UI.Panel(parent)
.SetSize(400, 300)
.SetBackgroundColor(new Color(0.15f, 0.15f, 0.2f, 0.95f))
.SetRounded(10)
.WithVerticalLayout(layout => layout
.SetPadding(10)
.SetSpacing(8)
.SetChildAlignment(TextAnchor.UpperCenter))
.Build();
// Grid layout
var grid = UI.Panel(parent)
.SetSize(400, 400)
.WithGridLayout(layout => layout
.SetCellSize(90, 90)
.SetSpacing(5, 5)
.SetPadding(10))
.Build();
```
--------------------------------
### Build bGUI Project with .NET CLI
Source: https://github.com/ifbars/bgui/blob/master/README.md
Commands to restore dependencies and build the bGUI project in Debug or Release configurations using the .NET CLI. Ensure your project's .csproj file has correct paths to Unity and MelonLoader DLLs.
```bash
# Restore dependencies
dotnet restore
# Debug build
dotnet build bGUI.sln -c Debug
# Release build
dotnet build bGUI.sln -c Release
```