### FairyGUI Graphics Setup with UIPackage in C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Initializes FairyGUI graphics system by loading UI packages and accessing main view component from UIPanel. Required setup for all GGraph drawing operations in the scene. ```csharp using UnityEngine; using FairyGUI; public class GraphicsExample : MonoBehaviour { public Gradient lineGradient; void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; ``` -------------------------------- ### Use Controllers for State Management in Unity with FairyGUI Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Switch between different visual states of UI components using controllers, enabling dynamic UI behavior without extensive code. This C# script demonstrates how to get, manipulate, and listen to controller changes in FairyGUI. It requires the FairyGUI package and a Unity project setup. ```csharp using UnityEngine; using FairyGUI; public class ControllerExample : MonoBehaviour { void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; // Get controller by name Controller viewController = mainView.GetController("c1"); // Switch pages by index viewController.selectedIndex = 1; // Switch pages by name viewController.selectedPage = "SettingsPage"; // Get controller info Debug.Log($"Total pages: {viewController.pageCount}"); Debug.Log($"Current page: {viewController.selectedPage}"); Debug.Log($"Previous index: {viewController.previousIndex}"); // Listen to page changes viewController.onChanged.Add(() => { Debug.Log($"Page changed to: {viewController.selectedPage}"); HandlePageChange(viewController.selectedIndex); }); // Button-controlled navigation mainView.GetChild("btnNext").onClick.Add(() => { int nextIndex = (viewController.selectedIndex + 1) % viewController.pageCount; viewController.selectedIndex = nextIndex; }); mainView.GetChild("btnPrev").onClick.Add(() => { int prevIndex = viewController.selectedIndex - 1; if (prevIndex < 0) prevIndex = viewController.pageCount - 1; viewController.selectedIndex = prevIndex; }); // Direct page access mainView.GetChild("btnHome").onClick.Add(() => { viewController.selectedPage = "HomePage"; }); // Using controllers for component states GButton btn = mainView.GetChild("stateButton").asButton; Controller btnState = btn.GetController("button"); // Controller states: up, down, over, disabled, selected_over, etc. // Usually automatically managed by button component } void HandlePageChange(int pageIndex) { switch (pageIndex) { case 0: Debug.Log("Showing home page"); break; case 1: Debug.Log("Showing settings page"); break; case 2: Debug.Log("Showing help page"); break; } } } ``` -------------------------------- ### Control Fairygui Transitions and Animations in Unity C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Demonstrates how to play, reverse, stop, pause, and resume transitions in Fairygui for Unity. It covers getting transitions by name, setting playback properties like speed and play times, and handling completion callbacks. This requires the Unity game engine and the Fairygui SDK. ```csharp using UnityEngine; using FairyGUI; public class TransitionExample : MonoBehaviour { private Transition _transition; private Transition _loopTransition; void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; // Get transition by name _transition = mainView.GetTransition("show"); _loopTransition = mainView.GetChild("animPanel").asCom.GetTransition("t0"); // Play once _transition.Play(); // Play with completion callback _transition.Play(() => { Debug.Log("Transition completed"); }); // Play multiple times with delay _transition.Play(3, 0.5f, () => { Debug.Log("Played 3 times with 0.5s delay"); }); // Loop forever _loopTransition.Play(int.MaxValue, 0, null); // Play in reverse _transition.PlayReverse(); _transition.PlayReverse(() => { Debug.Log("Reverse playback completed"); }); // Stop transition mainView.GetChild("btnStop").onClick.Add(() => { _transition.Stop(); // Or stop at completion state // _transition.Stop(setToComplete: true); }); // Pause/Resume mainView.GetChild("btnPause").onClick.Add(() => { _transition.SetPaused(true); }); mainView.GetChild("btnResume").onClick.Add(() => { _transition.SetPaused(false); }); // Configure transition properties _transition.timeScale = 2.0f; // Play at 2x speed _transition.ignoreEngineTimeScale = true; // Ignore Time.timeScale // Auto-play on show _transition.SetAutoPlay(true, times: 1, delay: 0.5f); // Change play times dynamically _transition.ChangePlayTimes(5); // Check state if (_transition.playing) { Debug.Log("Transition is playing"); } // Stop when component removed mainView.onRemovedFromStage.Add(() => { _loopTransition.Stop(); }); } } ``` -------------------------------- ### Create and Populate Virtual Scrollable List in Unity C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt This C# script demonstrates setting up a virtual scrollable list using FairyGUI in Unity. It handles data binding, item rendering, and user interaction for large datasets. Dependencies include the FairyGUI SDK for Unity and standard Unity libraries. The script expects a UI setup with a 'mailList' GList and defines custom item rendering logic. ```csharp using UnityEngine; using FairyGUI; using System.Collections.Generic; public class VirtualListExample : MonoBehaviour { private GList _list; private List _mailData; void Start() { UIPackage.AddPackage("UI/VirtualList"); // Register custom item class UIObjectFactory.SetPackageItemExtension("ui://VirtualList/mailItem", typeof(MailItem)); GComponent mainView = GetComponent().ui; _list = mainView.GetChild("mailList").asList; // Enable virtual list mode _list.SetVirtual(); // Or enable loop mode for circular scrolling // _list.SetVirtualAndLoop(); // Set item renderer callback _list.itemRenderer = RenderListItem; // Prepare data _mailData = new List(); for (int i = 0; i < 1000; i++) { _mailData.Add(new MailData { id = i, title = $"Mail {i}", sender = $"User{i}", read = i % 2 == 0, fetched = i % 3 == 0, time = System.DateTime.Now.AddHours(-i).ToString() }); } // Set total item count (virtual items) _list.numItems = _mailData.Count; // Configure list layout _list.layout = ListLayoutType.SingleColumn; _list.lineGap = 5; _list.defaultItem = "ui://VirtualList/mailItem"; // Selection handling _list.selectionMode = ListSelectionMode.Single; _list.onClickItem.Add(OnItemClicked); // Scroll to specific item mainView.GetChild("btnScrollTop").onClick.Add(() => { _list.scrollPane.ScrollTop(); }); mainView.GetChild("btnScrollBottom").onClick.Add(() => { _list.scrollPane.ScrollBottom(); }); mainView.GetChild("btnScrollTo500").onClick.Add(() => { _list.AddSelection(500, true); // Select and scroll to item 500 }); } void RenderListItem(int index, GObject obj) { MailItem item = (MailItem)obj; MailData data = _mailData[index]; // Update item appearance based on data item.title = data.title; item.SetSender(data.sender); item.SetRead(data.read); item.SetFetched(data.fetched); item.SetTime(data.time); // Store data reference item.data = data; } void OnItemClicked(EventContext context) { int index = _list.GetChildIndex((GObject)context.data); MailData data = _mailData[index]; Debug.Log($"Clicked mail: {data.title}"); } } public class MailData { public int id; public string title; public string sender; public bool read; public bool fetched; public string time; } // Custom item class public class MailItem : GButton { private GTextField _titleField; private GTextField _senderField; private GTextField _timeField; private Controller _readController; private Controller _fetchController; public override void ConstructFromXML(FairyGUI.Utils.XML xml) { base.ConstructFromXML(xml); _titleField = GetChild("title").asTextField; _senderField = GetChild("sender").asTextField; _timeField = GetChild("time").asTextField; _readController = GetController("read"); _fetchController = GetController("fetch"); } public void SetSender(string value) { _senderField.text = value; } public void SetTime(string value) { _timeField.text = value; } public void SetRead(bool value) { _readController.selectedIndex = value ? 1 : 0; } public void SetFetched(bool value) { _fetchController.selectedIndex = value ? 1 : 0; } } ``` -------------------------------- ### Non-Modal Window Creation in FairyGUI Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Creates a simple non-modal window by extending GWindow and setting modal property to false. Demonstrates minimal window initialization with content pane setup, centering, and close button configuration. Non-modal windows allow interaction with other UI elements while open. ```csharp public class Window2 : GWindow { protected override void OnInit() { this.contentPane = UIPackage.CreateObject("Basics", "WindowB").asCom; this.Center(); // Non-modal window this.modal = false; // Auto close button this.closeButton = contentPane.GetChild("btnClose"); } } ``` -------------------------------- ### Drag and Drop Interactions with FairyGUI Unity Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Demonstrates complete drag and drop implementation using FairyGUI in Unity. Covers simple draggable objects, bounded dragging with custom bounds, custom drag agents with icons, drop targets with data handling, visual feedback on drag enter/leave, custom drag proxies, and drag cancellation via keyboard input. Requires FairyGUI package and UIPanel component setup. ```csharp using UnityEngine; using FairyGUI; public class DragDropExample : MonoBehaviour { void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; // Simple draggable object GObject simpleItem = mainView.GetChild("a"); simpleItem.draggable = true; // Drag with custom bounds GObject boundedItem = mainView.GetChild("d").asButton; boundedItem.draggable = true; GObject boundsObj = mainView.GetChild("bounds"); Rect bounds = boundsObj.TransformRect( new Rect(0, 0, boundsObj.width, boundsObj.height), GRoot.inst ); boundedItem.dragBounds = bounds; // Custom drag with agent (shows different icon while dragging) GButton dragButton = mainView.GetChild("b").asButton; dragButton.draggable = true; dragButton.onDragStart.Add((EventContext context) => { // Cancel default dragging context.PreventDefault(); // Start custom drag with agent string icon = dragButton.icon; object data = new { itemId = 123, type = "weapon" }; DragDropManager.inst.StartDrag(dragButton, icon, icon, data); }); // Drop target GButton dropTarget = mainView.GetChild("c").asButton; dropTarget.icon = null; dropTarget.onDrop.Add((EventContext context) => { // Get dropped data object droppedData = context.data; if (droppedData is string iconUrl) { dropTarget.icon = iconUrl; Debug.Log($"Dropped icon: {iconUrl}"); } else { var data = droppedData as dynamic; Debug.Log($"Dropped item ID: {data.itemId}"); } }); // Visual feedback during drag over dropTarget.onDragEnter.Add(() => { dropTarget.GetChild("frame").asImage.color = Color.green; }); dropTarget.onDragLeave.Add(() => { dropTarget.GetChild("frame").asImage.color = Color.white; }); // Advanced: Custom drag proxy GObject customDrag = mainView.GetChild("customItem"); customDrag.onDragStart.Add((EventContext context) => { context.PreventDefault(); // Create custom drag proxy GObject proxy = UIPackage.CreateObject("Basics", "DragProxy"); proxy.alpha = 0.7f; DragDropManager.inst.StartDrag( customDrag, proxy.icon, proxy.icon, new { name = "Custom Item", value = 999 } ); }); // Cancel drag Stage.inst.onKeyDown.Add((EventContext context) => { if (context.inputEvent.keyCode == KeyCode.Escape) { if (DragDropManager.inst.dragging) { DragDropManager.inst.Cancel(); } } }); // Check if currently dragging if (DragDropManager.inst.dragging) { GObject dragAgent = DragDropManager.inst.agent; Debug.Log("Dragging in progress"); } } } ``` -------------------------------- ### Manipulate UI Object Properties - FairyGUI Unity C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Demonstrates comprehensive control of FairyGUI UI object properties including position, size, rotation, scale, alpha, visibility, and data binding. This example loads a UI package, creates a UI object, and applies various transformations and property modifications. Requires FairyGUI plugin and a valid UI package resource. ```csharp using UnityEngine; using FairyGUI; public class ObjectManipulation : MonoBehaviour { void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; GObject obj = UIPackage.CreateObject("Basics", "Component1"); mainView.AddChild(obj); // Position obj.SetXY(100, 200); obj.x = 150; // Individual axis obj.y = 250; obj.SetPosition(100, 200, 0); // With Z coordinate obj.Center(); // Center on parent obj.MakeFullScreen(); // Fill entire screen // Size obj.SetSize(400, 300); obj.width = 500; obj.height = 400; float actualW = obj.actualWidth; // Including scale float actualH = obj.actualHeight; // Scale obj.SetScale(2.0f, 2.0f); obj.scaleX = 1.5f; obj.scaleY = 1.5f; // Rotation obj.rotation = 45; // Z-axis rotation in degrees obj.rotationX = 30; obj.rotationY = 60; // Pivot point obj.SetPivot(0.5f, 0.5f); // Center pivot obj.SetPivot(0, 0, true); // Top-left as anchor // Appearance obj.alpha = 0.5f; // 50% opacity obj.visible = true; obj.grayed = false; // Grayscale effect obj.touchable = true; // Enable interaction obj.enabled = true; // Text and icon (for components that support it) if (obj is GButton btn) { btn.title = "Click Me"; btn.text = "Button Text"; btn.icon = "ui://Basics/icon1"; } // Data binding obj.data = new { id = 123, name = "Player" }; obj.dataSource = customDataObject; // Coordinate transformation Vector2 globalPos = obj.LocalToGlobal(Vector2.zero); Vector2 localPos = obj.GlobalToLocal(new Vector2(100, 100)); // Sorting order (for depth control) obj.sortingOrder = 100; // Remove from parent obj.RemoveFromParent(); // Dispose when done obj.Dispose(); } } ``` -------------------------------- ### Control ScrollPane Position and Behavior in Unity C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt This C# script for Unity demonstrates how to control a FairyGUI ScrollPane. It covers scrolling to various positions, getting scroll dimensions, configuring scroll properties like decelerationRate and bouncebackEffect, handling scroll events, implementing pull-to-refresh, locking/unlocking touch and mouse wheel scrolling, and snapping to list items. It requires a Unity project with FairyGUI integrated and a UI setup with a ScrollPane. ```csharp using UnityEngine; using FairyGUI; public class ScrollPaneExample : MonoBehaviour { private ScrollPane _scrollPane; void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; GComponent scrollContainer = mainView.GetChild("scrollArea").asCom; _scrollPane = scrollContainer.scrollPane; // Scroll to positions mainView.GetChild("btnTop").onClick.Add(() => { _scrollPane.ScrollTop(animated: true); }); mainView.GetChild("btnBottom").onClick.Add(() => { _scrollPane.ScrollBottom(animated: true); }); mainView.GetChild("btnLeft").onClick.Add(() => { _scrollPane.ScrollLeft(animated: true); }); mainView.GetChild("btnRight").onClick.Add(() => { _scrollPane.ScrollRight(animated: true); }); // Scroll by percentage (0-1) mainView.GetChild("btnMiddle").onClick.Add(() => { _scrollPane.SetPercX(0.5f, animated: true); _scrollPane.SetPercY(0.5f, animated: true); }); // Scroll by pixel position mainView.GetChild("btn200").onClick.Add(() => { _scrollPane.SetPosX(200, animated: true); _scrollPane.SetPosY(100, animated: true); }); // Get current scroll position Debug.Log($"Position: ({_scrollPane.posX}, {_scrollPane.posY})"); Debug.Log($"Percentage: ({_scrollPane.percX}, {_scrollPane.percY})"); // Get dimensions Debug.Log($"View size: {_scrollPane.viewWidth} x {_scrollPane.viewHeight}"); Debug.Log($"Content size: {_scrollPane.contentWidth} x {_scrollPane.contentHeight}"); // Configure scroll properties _scrollPane.scrollStep = 50; // Pixels per scroll step _scrollPane.decelerationRate = 0.967f; // Inertia deceleration _scrollPane.bouncebackEffect = true; // Bounce at edges _scrollPane.touchEffect = true; // Enable touch dragging _scrollPane.mouseWheelEnabled = true; // Mouse wheel scrolling _scrollPane.pageMode = false; // Page-based vs continuous // Scroll events _scrollPane.onScroll.Add(() => { Debug.Log($"Scrolled to: ({_scrollPane.posX}, {_scrollPane.posY})"); }); _scrollPane.onScrollEnd.Add(() => { Debug.Log("Scroll ended"); }); // Pull to refresh _scrollPane.onPullDownRelease.Add(() => { Debug.Log("Pull down released - trigger refresh"); // Simulate loading GTween.DelayedCall(2.0f).OnComplete(() => { Debug.Log("Refresh complete"); }); }); _scrollPane.onPullUpRelease.Add(() => { Debug.Log("Pull up released - load more"); }); // Lock scrolling mainView.GetChild("btnLock").onClick.Add(() => { _scrollPane.touchEffect = false; _scrollPane.mouseWheelEnabled = false; }); // Unlock scrolling mainView.GetChild("btnUnlock").onClick.Add(() => { _scrollPane.touchEffect = true; _scrollPane.mouseWheelEnabled = true; }); // Snap to specific item in list GList list = scrollContainer.GetChild("list").asList; if (list != null) { int itemIndex = 10; list.AddSelection(itemIndex, scrollItToView: true); // Or get first visible item int firstVisible = list.GetFirstChildInView(); Debug.Log($"First visible item: {firstVisible}"); } } } ``` -------------------------------- ### Create Loop Lists for Circular Scrolling in Unity with FairyGUI Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Implement infinitely looping lists where items repeat in a circular pattern, ideal for carousels. This C# script enables virtual loop mode, sets a custom item renderer, and applies scroll effects for a dynamic visual experience. It requires the FairyGUI package and a Unity project setup. ```csharp using UnityEngine; using FairyGUI; public class LoopListExample : MonoBehaviour { private GList _list; void Start() { UIPackage.AddPackage("UI/LoopList"); GComponent mainView = GetComponent().ui; _list = mainView.GetChild("list").asList; // Enable virtual loop mode _list.SetVirtualAndLoop(); // Set item renderer _list.itemRenderer = RenderListItem; // Only 5 items, but they repeat infinitely _list.numItems = 5; // Add scroll effect _list.scrollPane.onScroll.Add(DoSpecialEffect); // Apply initial effect DoSpecialEffect(); // Display current item mainView.GetChild("txtCurrent").text = "1"; } void RenderListItem(int index, GObject obj) { GButton item = (GButton)obj; // Set pivot to center for scaling effect item.SetPivot(0.5f, 0.5f); // Set icon based on index (cycles through 5 items) item.icon = UIPackage.GetItemURL("LoopList", "n" + (index + 1)); // Item data item.title = $"Item {index + 1}"; } void DoSpecialEffect() { // Calculate middle X position of viewport float midX = _list.scrollPane.posX + _list.viewWidth / 2; // Scale items based on distance from center int cnt = _list.numChildren; for (int i = 0; i < cnt; i++) { GObject obj = _list.GetChildAt(i); float dist = Mathf.Abs(midX - obj.x - obj.width / 2); if (dist > obj.width) { // No intersection - normal size obj.SetScale(1, 1); } else { // Scale up to 1.24x when centered float scale = 1 + (1 - dist / obj.width) * 0.24f; obj.SetScale(scale, scale); } } // Update current item indicator int currentIndex = _list.GetFirstChildInView(); GameObject.Find("txtCurrent").GetComponent().text = ((currentIndex + 1) % _list.numItems).ToString(); } } ``` -------------------------------- ### Draw Pie Charts with EllipseMesh in C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Creates pie chart graphics using EllipseMesh factory by setting start and end degrees on the shape's mesh. Requires accessing the shape's graphics component and marking mesh as dirty for rendering updates. ```csharp GGraph pie = mainView.GetChild("pie").asGraph; Shape shape = pie.shape; EllipseMesh ellipse = shape.graphics.GetMeshFactory(); ellipse.startDegree = 30; ellipse.endDegreee = 300; shape.graphics.SetMeshDirty(); ``` -------------------------------- ### Draw Polygons with PolygonMesh in C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Constructs custom polygon shapes (trapezoid example) using PolygonMesh with normalized UV coordinates and texture mapping. Uses percentage-based positioning for scalable polygon vertices and applies textures from UI packages. ```csharp GGraph trapezoid = mainView.GetChild("trapezoid").asGraph; Shape shape = trapezoid.shape; PolygonMesh polygon = shape.graphics.GetMeshFactory(); polygon.usePercentPositions = true; polygon.points.Clear(); polygon.points.Add(new Vector2(0f, 1f)); polygon.points.Add(new Vector2(0.3f, 0)); polygon.points.Add(new Vector2(0.7f, 0)); polygon.points.Add(new Vector2(1f, 1f)); polygon.texcoords.Clear(); polygon.texcoords.AddRange(VertexBuffer.NormalizedUV); shape.graphics.SetMeshDirty(); shape.graphics.texture = (NTexture)UIPackage.GetItemAsset("Basics", "texture1"); ``` -------------------------------- ### Initialize FairyGUI and Load UI Packages in Unity Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Configures global UI settings, loads UI packages from the Resources folder, and sets up the design resolution. It also demonstrates creating UI objects synchronously from loaded packages using both component and URL formats. This is essential for setting up the initial UI environment. ```csharp using UnityEngine; using FairyGUI; public class GameInit : MonoBehaviour { void Awake() { // Set default font (Unity 5+) UIConfig.defaultFont = "Microsoft YaHei"; // Load UI package from Resources/UI/Basics folder UIPackage.AddPackage("UI/Basics"); // Configure global scrollbar resources UIConfig.verticalScrollBar = "ui://Basics/ScrollBar_VT"; UIConfig.horizontalScrollBar = "ui://Basics/ScrollBar_HZ"; // Set popup menu template UIConfig.popupMenu = "ui://Basics/PopupMenu"; // Configure button click sound UIConfig.buttonSound = (NAudioClip)UIPackage.GetItemAsset("Basics", "click"); // Set design resolution for responsive scaling GRoot.inst.SetContentScaleFactor(1280, 720); } void Start() { // Get UI component from UIPanel GComponent mainView = GetComponent().ui; // Create UI object by package and component name GObject obj = UIPackage.CreateObject("Basics", "MainPanel"); GRoot.inst.AddChild(obj); // Or create by URL format GObject btn = UIPackage.CreateObjectFromURL("ui://Basics/Button1"); mainView.AddChild(btn); } void OnDestroy() { // Unload package when done UIPackage.RemovePackage("UI/Basics"); } } ``` -------------------------------- ### Async Package and Object Loading in Unity with FairyGUI Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Demonstrates asynchronous loading of UI packages and UI objects to prevent main thread blocking. Includes callbacks for when packages and objects are successfully loaded, and shows an alternative method for custom resource loading logic, such as from AssetBundles. ```csharp using UnityEngine; using FairyGUI; using System.Collections; public class AsyncLoader : MonoBehaviour { void Start() { // Load package asynchronously UIPackage.AddPackageAsync("UI/Battle", OnPackageLoaded); } void OnPackageLoaded(UIPackage package) { Debug.Log($"Package loaded: {package.name}"); // Create object asynchronously after package is loaded UIPackage.CreateObjectAsync("Battle", "BattleUI", OnObjectCreated); } void OnObjectCreated(GObject obj) { if (obj != null) { GRoot.inst.AddChild(obj); obj.Center(); Debug.Log("Battle UI created and centered"); } } // Alternative: Custom resource loading function void LoadWithCustomFunction() { UIPackage.AddPackage("UI/Custom", CustomResourceLoader); } object CustomResourceLoader(string name, string extension, System.Type type, out UIPackage.DestroyMethod destroyMethod) { destroyMethod = UIPackage.DestroyMethod.Unload; // Custom loading logic (e.g., from AssetBundle) if (extension == ".png" && type == typeof(Texture2D)) { return Resources.Load($"Textures/{name}"); } else if (extension == ".wav" && type == typeof(AudioClip)) { return Resources.Load($"Audio/{name}"); } return null; } } ``` -------------------------------- ### Window Creation and Display Management in FairyGUI Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Creates and manages multiple window instances with show/hide functionality. Demonstrates lazy initialization of window objects and button event handling to display modal and non-modal windows. Windows are created from UI packages and support custom lifecycle callbacks. ```csharp using UnityEngine; using FairyGUI; public class WindowExample : MonoBehaviour { private Window1 _window1; private Window2 _window2; void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; // Show window 1 mainView.GetChild("btnWindow1").onClick.Add(() => { if (_window1 == null) _window1 = new Window1(); _window1.Show(); }); // Show window 2 mainView.GetChild("btnWindow2").onClick.Add(() => { if (_window2 == null) _window2 = new Window2(); _window2.Show(); }); } } ``` -------------------------------- ### Create and Display Popup Menus with FairyGUI Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Demonstrates creating a PopupMenu with multiple items and separators, then displaying it either anchored to a button or at the mouse position on right-click. The popup menu includes callback handlers for item selection and supports directional positioning relative to UI objects. ```csharp // Create popup menu _contextMenu = new PopupMenu(); _contextMenu.AddItem("New", OnMenuItemClick); _contextMenu.AddItem("Open", OnMenuItemClick); _contextMenu.AddItem("Save", OnMenuItemClick); _contextMenu.AddSeperator(); // Add separator line _contextMenu.AddItem("Exit", OnMenuItemClick); // Show popup menu on button click GButton menuBtn = mainView.GetChild("btnMenu").asButton; menuBtn.onClick.Add((EventContext context) => { _contextMenu.Show((GObject)context.sender, PopupDirection.Down); }); // Show menu on right-click anywhere mainView.onRightClick.Add(() => { _contextMenu.Show(); // Show at mouse position }); ``` -------------------------------- ### Handle Button Clicks and Touch Events in FairyGUI C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Complete event handling system for FairyGUI UI components in Unity. Demonstrates binding click listeners using method references and lambda expressions, accessing event context for detailed information, managing touch events with position tracking, implementing drag-and-drop functionality, and handling state changes for checkboxes and radio buttons. Requires FairyGUI package imported and UI components properly configured in the scene. ```csharp using UnityEngine; using FairyGUI; public class EventHandling : MonoBehaviour { void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; // Simple button click GButton btn1 = mainView.GetChild("btn_Start").asButton; btn1.onClick.Add(OnStartClicked); // Lambda expression for inline handling GButton btn2 = mainView.GetChild("btn_Close").asButton; btn2.onClick.Add(() => { Debug.Log("Close button clicked"); Application.Quit(); }); // Access event context for detailed information GButton btn3 = mainView.GetChild("btn_Action").asButton; btn3.onClick.Add((EventContext context) => { GButton sender = (GButton)context.sender; InputEvent evt = context.inputEvent; Debug.Log($"Button {sender.title} clicked at {evt.position}"); // Prevent event bubbling context.StopPropagation(); }); // Touch events for custom interactions GObject touchArea = mainView.GetChild("touchArea"); touchArea.onTouchBegin.Add(OnTouchBegin); touchArea.onTouchMove.Add(OnTouchMove); touchArea.onTouchEnd.Add(OnTouchEnd); // Drag and drop GObject draggable = mainView.GetChild("dragItem"); draggable.draggable = true; draggable.onDragStart.Add((EventContext context) => { Debug.Log("Drag started"); }); draggable.onDragEnd.Add((EventContext context) => { Debug.Log($"Drag ended at {context.sender.position}"); }); // Right-click handling mainView.onRightClick.Add(() => { Debug.Log("Right-clicked on main view"); }); // Checkbox and radio button state change GButton checkbox = mainView.GetChild("checkbox").asButton; checkbox.onChanged.Add(() => { Debug.Log($"Checkbox state: {checkbox.selected}"); }); } void OnStartClicked() { Debug.Log("Start game"); } void OnTouchBegin(EventContext context) { InputEvent evt = context.inputEvent; Debug.Log($"Touch began at: {evt.position}"); } void OnTouchMove(EventContext context) { InputEvent evt = context.inputEvent; Vector2 delta = evt.position - evt.lastPosition; Debug.Log($"Touch moved by: {delta}"); } void OnTouchEnd(EventContext context) { Debug.Log("Touch ended"); } } ``` -------------------------------- ### Unity C# GTween System for Custom Animations Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Demonstrates various uses of the GTween system in Unity with FairyGUI for animating GObjects. Includes simple tweens for movement, fading, scaling, rotation, resizing, advanced tweens with custom update logic, shake effects, delayed calls, tween management (kill), and tween sequences. Requires Unity and FairyGUI packages. ```csharp using UnityEngine; using FairyGUI; public class TweenExample : MonoBehaviour { private GObject _obj; void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; _obj = mainView.GetChild("box"); // Simple move tween _obj.TweenMove(new Vector2(300, 200), 1.0f); // Move X axis only _obj.TweenMoveX(500, 1.0f); // Fade tween _obj.TweenFade(0.3f, 1.0f); // Fade to 30% alpha in 1 second // Scale tween _obj.TweenScale(new Vector2(2, 2), 1.0f); // Rotate tween _obj.TweenRotate(360, 2.0f); // Resize tween _obj.TweenResize(new Vector2(400, 300), 1.0f); // Advanced tween with full control GTween.To(0, 100, 2.0f) .SetTarget(_obj) .SetEase(EaseType.QuadOut) .SetDelay(0.5f) .OnUpdate((GTweener tweener) => { // Custom update logic float value = tweener.value.x; _obj.alpha = value / 100f; }) .OnComplete(() => { Debug.Log("Tween completed"); }); // Shake effect Vector3 originalPos = _obj.position; GTween.Shake(originalPos, amplitude: 10, duration: 0.5f) .SetTarget(_obj) .OnUpdate((GTweener tweener) => { _obj.SetPosition(tweener.value.x, tweener.value.y, 0); }); // Delayed call GTween.DelayedCall(2.0f).OnComplete(() => { Debug.Log("Executed after 2 seconds"); }); // Kill all tweens on object mainView.GetChild("btnStop").onClick.Add(() => { GTween.Kill(_obj); }); // Kill specific tween GTweener tweener = _obj.TweenMove(new Vector2(100, 100), 3.0f); mainView.GetChild("btnCancel").onClick.Add(() => { tweener.Kill(); }); // Sequence of tweens _obj.TweenMove(new Vector2(200, 100), 1.0f) .OnComplete(() => { _obj.TweenMove(new Vector2(300, 200), 1.0f) .OnComplete(() => { _obj.TweenFade(0, 0.5f); }); }); // Vector3 tween GTween.To(Vector3.zero, new Vector3(10, 20, 30), 2.0f) .SetEase(EaseType.ExpoOut) .OnUpdate((GTweener t) => { Vector3 value = t.value.vec3; Debug.Log($"Tweening: {value}"); }); } } ``` -------------------------------- ### Show Tooltips on Hover with FairyGUI Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Demonstrates showing and hiding simple text tooltips on mouse hover events (onRollOver/onRollOut). Also includes creating a custom tooltip window from UI package and displaying it with ShowTooltipsWin() for more complex tooltip UI. ```csharp // Show tooltip GObject hoverItem = mainView.GetChild("item"); hoverItem.onRollOver.Add(() => { GRoot.inst.ShowTooltips("This is a tooltip"); }); hoverItem.onRollOut.Add(() => { GRoot.inst.HideTooltips(); }); // Custom tooltip window GObject tooltipWin = UIPackage.CreateObject("Basics", "TooltipWin"); hoverItem.onRollOver.Add(() => { GRoot.inst.ShowTooltipsWin(tooltipWin); }); ``` -------------------------------- ### Display Custom Popup Panels with Modal Background Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Creates a custom popup panel from UI package and displays it with modal background using GRoot.ShowPopup(). Includes a close button handler and demonstrates toggling popup visibility with directional positioning relative to a button. ```csharp // Custom popup panel _popupPanel = UIPackage.CreateObject("Basics", "PopupPanel").asCom; _popupPanel.Center(); GButton popupBtn = mainView.GetChild("btnPopup").asButton; popupBtn.onClick.Add(() => { // Show popup with modal background GRoot.inst.ShowPopup(_popupPanel); }); // Close popup button _popupPanel.GetChild("btnClose").onClick.Add(() => { GRoot.inst.HidePopup(_popupPanel); }); // Toggle popup GButton toggleBtn = mainView.GetChild("btnToggle").asButton; toggleBtn.onClick.Add(() => { GRoot.inst.TogglePopup(_popupPanel, toggleBtn, PopupDirection.Up); }); ``` -------------------------------- ### Custom Modal Window with Animation and Lifecycle in FairyGUI Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Defines a custom modal window class with initialization, show/hide animations, and event handlers. Supports drag functionality, close buttons, and custom tween-based animations for smooth transitions. Includes lifecycle callbacks for window shown and hide events. ```csharp public class Window1 : GWindow { private GButton _closeButton; private GButton _actionButton; protected override void OnInit() { // Set content pane from UI package this.contentPane = UIPackage.CreateObject("Basics", "WindowA").asCom; // Center the window this.Center(); // Set modal mode this.modal = true; // Set close button (auto-closes window on click) this.closeButton = contentPane.GetChild("btnClose"); // Set drag area for window dragging this.dragArea = contentPane.GetChild("dragArea"); // Setup content _actionButton = contentPane.GetChild("btnAction").asButton; _actionButton.onClick.Add(OnActionClick); } protected override void OnShown() { // Called after show animation completes Debug.Log("Window shown"); } protected override void OnHide() { // Called when hide begins Debug.Log("Window hiding"); } protected override void DoShowAnimation() { // Custom show animation this.SetScale(0.1f, 0.1f); GTween.To(new Vector2(0.1f, 0.1f), Vector2.one, 0.3f) .SetTarget(this) .SetEase(EaseType.QuadOut) .OnUpdate((GTweener t) => { this.SetScale(t.value.x, t.value.y); }) .OnComplete(() => { this.OnShown(); }); } protected override void DoHideAnimation() { // Custom hide animation GTween.To(Vector2.one, new Vector2(0.1f, 0.1f), 0.3f) .SetTarget(this) .SetEase(EaseType.QuadIn) .OnUpdate((GTweener t) => { this.SetScale(t.value.x, t.value.y); }) .OnComplete(() => { this.HideImmediately(); }); } void OnActionClick() { Debug.Log("Action button clicked"); this.Hide(); } } ``` -------------------------------- ### Configure and Populate Standard List with Object Pooling Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Sets up a FairyGUI GList component with object pooling, configures horizontal flow layout with spacing, and populates items from a data source. Uses AddItemFromPool() to reuse list item objects instead of creating new ones, improving memory efficiency and performance during frequent add/remove operations. ```csharp using UnityEngine; using FairyGUI; public class StandardListExample : MonoBehaviour { private GList _list; void Start() { UIPackage.AddPackage("UI/Basics"); GComponent mainView = GetComponent().ui; _list = mainView.GetChild("list1").asList; // Configure layout _list.layout = ListLayoutType.FlowHorizontal; _list.lineGap = 10; _list.columnGap = 10; _list.lineCount = 5; // 5 items per row // Clear list using object pool _list.RemoveChildrenToPool(); // Populate list with pooled objects string[] platforms = System.Enum.GetNames(typeof(RuntimePlatform)); Color[] colors = { Color.yellow, Color.red, Color.white, Color.cyan }; for (int i = 0; i < platforms.Length; i++) { // Get item from pool (creates if not available) GButton item = _list.AddItemFromPool().asButton; item.GetChild("t0").text = (i + 1).ToString(); item.GetChild("t1").text = platforms[i]; item.GetChild("t2").asTextField.color = colors[Random.Range(0, 4)]; GProgressBar star = item.GetChild("star").asProgress; star.value = Random.Range(1, 4) * 33; // Bind data for later retrieval item.data = new { index = i, platform = platforms[i] }; // Item click handler item.onClick.Add(() => { Debug.Log($"Clicked: {platforms[i]}"); }); } // Selection mode _list.selectionMode = ListSelectionMode.Multiple; _list.onClickItem.Add(OnListItemClick); // Get selected items Debug.Log($"Selected indices: {string.Join(", ", _list.GetSelection())}"); Debug.Log($"Selected index: {_list.selectedIndex}"); // Add/remove items dynamically mainView.GetChild("btnAdd").onClick.Add(AddItem); mainView.GetChild("btnRemove").onClick.Add(RemoveSelectedItems); mainView.GetChild("btnClear").onClick.Add(() => { _list.RemoveChildrenToPool(); // Return all to pool }); } void OnListItemClick(EventContext context) { GObject item = (GObject)context.data; Debug.Log($"List item clicked at index: {_list.GetChildIndex(item)}"); } void AddItem() { GButton newItem = _list.AddItemFromPool().asButton; newItem.title = $"New Item {_list.numChildren}"; } void RemoveSelectedItems() { List indices = _list.GetSelection(); // Remove in reverse order to maintain indices for (int i = indices.Count - 1; i >= 0; i--) { _list.RemoveChildToPoolAt(indices[i]); } } } ``` -------------------------------- ### Create Dynamic Graphics at Runtime in C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Generates random shapes dynamically at runtime using button callbacks. Creates new GGraph instances with random positions and colors, demonstrating procedural graphics generation. ```csharp GButton createBtn = mainView.GetChild("btnCreate").asButton; createBtnBtn.onClick.Add(() => { GGraph newShape = new GGraph(); newShape.SetXY(Random.Range(0, 500), Random.Range(0, 400)); newShape.DrawRect(100, 100, 1, Color.black, Random.ColorHSV()); mainView.AddChild(newShape); }); ``` -------------------------------- ### Draw Rectangles and Circles with GGraph in C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Demonstrates drawing basic shapes (rectangles and circles) using GGraph component in FairyGUI. Uses DrawRect and DrawEllipse methods with custom line widths, line colors, and fill colors. Requires FairyGUI package to be loaded and component references to be available. ```csharp // Draw rectangle GGraph rect = mainView.GetChild("rect").asGraph; rect.DrawRect(200, 150, lineWidth: 2, lineColor: Color.black, fillColor: Color.red); // Draw circle GGraph circle = mainView.GetChild("circle").asGraph; circle.DrawEllipse(100, 100, lineColor: Color.blue, fillColor: Color.yellow); ``` -------------------------------- ### Draw Straight Lines with LineMesh in C# Source: https://context7.com/gameframex/com.gameframex.unity.fairygui.unity/llms.txt Creates straight line segments using LineMesh with CurveType.Straight and rounded edges. Demonstrates multi-segment line paths with precise positioning and mesh refresh. ```csharp GGraph straightLine = mainView.GetChild("straightLine").asGraph; Shape shape = straightLine.shape; LineMesh lineMesh = shape.graphics.GetMeshFactory(); lineMesh.lineWidth = 3; lineMesh.roundEdge = true; lineMesh.path.Create(new GPathPoint[] { new GPathPoint(new Vector3(0, 0, 0), GPathPoint.CurveType.Straight), new GPathPoint(new Vector3(100, 50, 0), GPathPoint.CurveType.Straight), new GPathPoint(new Vector3(200, 0, 0), GPathPoint.CurveType.Straight) }); shape.graphics.SetMeshDirty(); ```