### Convert Figma Components to Unity UI with CustomComponentConverter Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Implement a custom `ComponentConverter` to map Figma components by their type ID to specific Unity UI components. This example converts a 'ProgressBar' type to a Unity `Slider`. ```csharp using Cdm.Figma; using Cdm.Figma.UI; using UnityEngine; using UnityEngine.UI; // Custom converter for a "ProgressBar" component type set in Figma public class ProgressBarComponentConverter : ComponentConverter { protected override bool CanConvertType(string typeId) { // Match components with type "ProgressBar" (set via Unity Figma Plugin) return typeId == "ProgressBar"; } protected override FigmaNode Convert(FigmaNode parentObject, InstanceNode instanceNode, NodeConvertArgs args) { // Let base converter handle the basic frame conversion var nodeObject = base.Convert(parentObject, instanceNode, args); if (nodeObject == null) return null; // Add custom Slider component configured as progress bar var slider = nodeObject.gameObject.AddComponent(); slider.interactable = false; // Progress bars are usually non-interactive slider.transition = Selectable.Transition.None; // Find fill image by binding key var fillImage = nodeObject.Query("Fill"); if (fillImage != null) { slider.fillRect = fillImage.rectTransform; } // Find background by binding key var backgroundImage = nodeObject.Query("Background"); if (backgroundImage != null) { // Configure background } slider.minValue = 0f; slider.maxValue = 1f; slider.value = 0.5f; return nodeObject; } } ``` ```csharp // Usage public class CustomComponentExample : MonoBehaviour { public FigmaDesign ImportWithCustomComponent(FigmaFile file) { var importer = new FigmaImporter(); // Add custom component converter importer.componentConverters.Add(new ProgressBarComponentConverter()); importer.AddDefaultNodeConverters(); importer.AddDefaultComponentConverters(); return importer.ImportFile(file); } } ``` -------------------------------- ### Interact with Figma REST API using FigmaApi Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Use FigmaApi to download file JSON, render specific nodes as images, or retrieve image fills. Requires a valid personal access token and file ID. ```csharp using Cdm.Figma; using System.Threading.Tasks; using UnityEngine; public class FigmaApiExample : MonoBehaviour { private const string PersonalAccessToken = "figd_xxxxxxxxxxxxxxxxx"; private const string FileId = "abc123XYZ"; // From Figma URL: figma.com/file/:key/:title async void Start() { using var figmaApi = new FigmaApi(PersonalAccessToken); // Download a Figma file as JSON var fileRequest = new FileRequest(FileId) { version = "", // Optional: specific version ID geometry = "paths", // Export vector data depth = null, // Traverse all nodes (or set 1 for pages only, 2 for top-level objects) includeBranchData = true }; string fileJson = await figmaApi.GetFileAsync(fileRequest); Debug.Log($"Downloaded file JSON: {fileJson.Length} characters"); // Render specific nodes as images var imageRequest = new ImageRequest(FileId) { ids = new[] { "1:2", "3:4" }, // Node IDs to render scale = 2f, // Scale factor (0.01-4) format = "png", // jpg, png, svg, or pdf svgIncludeId = false, svgSimplifyStroke = true, useAbsoluteBounds = false }; var images = await figmaApi.GetImageAsync(imageRequest); foreach (var (nodeId, imageData) in images) { if (imageData != null) { Debug.Log($"Node {nodeId}: {imageData.Length} bytes"); } } // Download all image fills from a document var imageFillsRequest = new ImageFillsRequest(FileId); var imageFills = await figmaApi.GetImageFillsAsync(imageFillsRequest); Debug.Log($"Downloaded {imageFills.Count} image fills"); } } ``` -------------------------------- ### Import Figma File to Unity UI Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Converts a parsed FigmaFile into Unity UI GameObjects using FigmaImporter. This includes configuring node and component converters, font mappings, sprite generation options, error handling, and layer settings. Requires Cdm.Figma, Cdm.Figma.UI, Cdm.Figma.Utils, TMPro, and UnityEngine namespaces. ```csharp using Cdm.Figma; using Cdm.Figma.UI; using Cdm.Figma.Utils; using TMPro; using UnityEngine; public class FigmaImporterExample : MonoBehaviour { [SerializeField] private TMP_FontAsset defaultFont; [SerializeField] private TMP_FontAsset robotoFont; public FigmaDesign ImportFigmaFile(FigmaFile file) { var importer = new FigmaImporter(); // Add default node converters (Page, Frame, Group, Text, Vector, etc.) importer.AddDefaultNodeConverters(); // Add default component converters (Button, Toggle, Slider, InputField, etc.) importer.AddDefaultComponentConverters(); // Configure font mappings importer.fonts.Add(new FontSource { fontName = "Roboto", font = robotoFont }); importer.fallbackFont = defaultFont; // Configure sprite generation options importer.spriteOptions = new SpriteGenerateOptions { tessellationOptions = new Unity.VectorGraphics.VectorUtils.TessellationOptions { StepDistance = 1.0f, MaxCordDeviation = 0.5f, MaxTanAngleDeviation = 0.1f, SamplingStepSize = 0.01f }, filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp, minTextureSize = 64, maxTextureSize = 256, rectTextureSize = 32, rectResolutionScale = 1f, sampleCount = 4, gradientResolution = 128, pixelsPerUnit = 100f, scaleFactor = 1f, expandEdges = false }; // Set error handling behavior importer.failOnError = false; // Log errors instead of throwing // Set UI layer for generated GameObjects importer.layer = LayerMask.NameToLayer("UI"); // Import specific pages only (optional) var options = new IFigmaImporter.Options { selectedPages = new[] { "1:2", "3:4" } // Page node IDs, or null for all pages }; // Import the file FigmaDesign design = importer.ImportFile(file, options); // Access generated assets Debug.Log($ } } } ``` -------------------------------- ### Download complete Figma files using FigmaDownloader Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Use FigmaDownloader to retrieve a fully parsed FigmaFile object, including dependencies and images. Supports progress tracking via the IProgress interface. ```csharp using Cdm.Figma; using System; using System.Threading.Tasks; using UnityEngine; public class FigmaDownloaderExample : MonoBehaviour { private const string PersonalAccessToken = "figd_xxxxxxxxxxxxxxxxx"; private const string FileId = "abc123XYZ"; async void Start() { var downloader = new FigmaDownloader { downloadDependencies = true, // Download external components from other files downloadImages = true // Download all image fills }; // Track download progress var progress = new Progress(p => { Debug.Log($"Downloading {p.fileId}: {p.progress * 100:F0}% (Dependency: {p.isDependency})"); }); try { FigmaFile figmaFile = await downloader.DownloadFileAsync( PersonalAccessToken, FileId, fileVersion: "", // Empty for latest version progress: progress ); Debug.Log($"File: {figmaFile.name}"); Debug.Log($"Version: {figmaFile.version}"); Debug.Log($"Last Modified: {figmaFile.lastModified}"); Debug.Log($"Pages: {figmaFile.document.children.Length}"); Debug.Log($"Components: {figmaFile.components.Count}"); Debug.Log($"Component Sets: {figmaFile.componentSets.Count}"); Debug.Log($"Images: {figmaFile.images.Count}"); Debug.Log($"Dependencies: {figmaFile.fileDependencies?.Length ?? 0}"); } catch (Exception ex) { Debug.LogError($"Download failed: {ex.Message}"); } } } ``` -------------------------------- ### Parse and Navigate Figma File Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Parses a Figma JSON string into a FigmaFile object and demonstrates how to navigate its document hierarchy, access components, styles, and serialize it back to JSON. Requires the Cdm.Figma namespace. ```csharp using Cdm.Figma; using UnityEngine; public class FigmaFileExample : MonoBehaviour { public void ParseAndNavigate(string jsonContent) { // Parse JSON into FigmaFile FigmaFile file = FigmaFile.Parse(jsonContent); // Build the node hierarchy (required before using componentNodes/componentSetNodes) file.BuildHierarchy(); // Access document metadata Debug.Log($ ``` -------------------------------- ### Create Custom UI Behaviors with FigmaBehaviour Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Extend FigmaBehaviour to create custom MonoBehaviour scripts that automatically bind to Figma nodes using attributes. Attach this script to a Figma node and use binding keys to link UI elements. ```csharp using Cdm.Figma.UI; using TMPro; using UnityEngine; using UnityEngine.UI; // Custom behaviour that auto-binds to child nodes via binding keys public class CardBehaviour : FigmaBehaviour { // Use FigmaNode attribute to auto-bind fields by binding key [FigmaNode("Title")] private TMP_Text titleText; [FigmaNode("Description")] private TMP_Text descriptionText; [FigmaNode("Icon")] private Image iconImage; [FigmaNode("ActionButton")] private Button actionButton; [FigmaNode("CloseButton")] private Button closeButton; // Public properties for runtime access public string Title { get => titleText?.text; set { if (titleText != null) titleText.text = value; } } public string Description { get => descriptionText?.text; set { if (descriptionText != null) descriptionText.text = value; } } public Sprite Icon { get => iconImage?.sprite; set { if (iconImage != null) iconImage.sprite = value; } } protected override void Awake() { base.Awake(); // Performs auto-binding // Setup button listeners actionButton?.onClick.AddListener(OnActionClicked); closeButton?.onClick.AddListener(OnCloseClicked); } private void OnActionClicked() { Debug.Log($"Action clicked on card: {Title}"); } private void OnCloseClicked() { gameObject.SetActive(false); } } // Usage - attach CardBehaviour to a Figma node with the appropriate binding keys public class FigmaBehaviourExample : MonoBehaviour { [SerializeField] private FigmaDesign figmaDesign; void Start() { // Query and configure the card var card = figmaDesign.Query("UserCard"); if (card != null) { card.Title = "Welcome!"; card.Description = "This card was populated at runtime."; } // Or create a new instance var newCard = figmaDesign.CreateInstance("CardTemplate", transform); newCard.Title = "New Card"; } } ``` -------------------------------- ### Configure Sprite Generation Options in C# Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Defines high-quality and performance-oriented configurations for vector-to-sprite conversion using SpriteGenerateOptions. ```csharp using Cdm.Figma.Utils; using Unity.VectorGraphics; using UnityEngine; public class SpriteOptionsExample : MonoBehaviour { public SpriteGenerateOptions GetHighQualityOptions() { return new SpriteGenerateOptions { // Tessellation settings for vector graphics tessellationOptions = new VectorUtils.TessellationOptions { StepDistance = 0.5f, // Lower = more detail MaxCordDeviation = 0.25f, // Maximum deviation from curves MaxTanAngleDeviation = 0.05f, // Tangent angle deviation SamplingStepSize = 0.005f // Sampling precision }, // Texture settings filterMode = FilterMode.Trilinear, wrapMode = TextureWrapMode.Clamp, // Texture size limits minTextureSize = 128, maxTextureSize = 512, rectTextureSize = 64, // Size for simple rectangles (9-slice sprites) rectResolutionScale = 2f, // Scale factor for corner radii/strokes // Anti-aliasing sampleCount = 8, // MSAA samples (1, 2, 4, 8) // Gradient quality gradientResolution = 256, // Gradient texture resolution // Unity units pixelsPerUnit = 100f, scaleFactor = 2f, // Scale for retina displays // Edge handling expandEdges = true // Prevents dark banding on edges }; } public SpriteGenerateOptions GetPerformanceOptions() { return new SpriteGenerateOptions { tessellationOptions = new VectorUtils.TessellationOptions { StepDistance = 2.0f, MaxCordDeviation = 1.0f, MaxTanAngleDeviation = 0.2f, SamplingStepSize = 0.02f }, filterMode = FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp, minTextureSize = 32, maxTextureSize = 128, rectTextureSize = 16, rectResolutionScale = 1f, sampleCount = 2, gradientResolution = 64, pixelsPerUnit = 100f, scaleFactor = 1f, expandEdges = false }; } } ``` -------------------------------- ### Accessing Figma Design and Nodes in Unity Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Use FigmaDesign and FigmaNode classes to query and access specific UI elements at runtime. Binding keys must be set in Figma using the Unity Figma Plugin. ```csharp using Cdm.Figma; using Cdm.Figma.UI; using TMPro; using UnityEngine; using UnityEngine.UI; public class FigmaDesignExample : MonoBehaviour { [SerializeField] private FigmaDesign figmaDesign; void Start() { // Access design metadata Debug.Log($ ``` -------------------------------- ### Extend Rectangle Node Import with CustomConverter Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Create a custom `NodeConverter` for `RectangleNode` to add an `Image` component, handle corner radius, and process fills. Add this converter to the `FigmaImporter` before default converters for higher priority. ```csharp using Cdm.Figma; using Cdm.Figma.UI; using UnityEngine; using UnityEngine.UI; // Custom converter for Rectangle nodes with special handling public class CustomRectangleConverter : NodeConverter { protected override FigmaNode Convert(FigmaNode parentObject, RectangleNode node, NodeConvertArgs args) { // Create the FigmaNode with RectTransform var figmaNode = args.importer.CreateFigmaNode(node); figmaNode.transform.SetParent(parentObject.rectTransform, false); // Set transform properties (position, size, rotation, scale) figmaNode.SetTransform(node); // Add Image component var image = figmaNode.gameObject.AddComponent(); // Handle corner radius for rounded rectangles if (node.cornerRadius > 0) { // Apply rounded sprite or custom shader Debug.Log($"Rectangle has corner radius: {node.cornerRadius}"); } // Handle fills if (node.fills != null && node.fills.Length > 0) { var fill = node.fills[0]; if (fill is SolidPaint solidPaint) { image.color = (Color)solidPaint.color; } } // Apply styles collected during conversion figmaNode.ApplyStyles(); return figmaNode; } } ``` ```csharp // Usage with FigmaImporter public class CustomConverterExample : MonoBehaviour { public FigmaDesign ImportWithCustomConverter(FigmaFile file) { var importer = new FigmaImporter(); // Add custom converter before default converters (higher priority) importer.nodeConverters.Add(new CustomRectangleConverter()); // Then add default converters importer.AddDefaultNodeConverters(); importer.AddDefaultComponentConverters(); return importer.ImportFile(file); } } ``` -------------------------------- ### Traverse Figma File Nodes (Parse-Time) Source: https://context7.com/cdmvision/unity-figma-importer/llms.txt Traverse the Figma node hierarchy at parse-time using DFS. This method allows access to node-specific properties like frame size and text content. You can filter nodes by type. ```csharp using Cdm.Figma; using Cdm.Figma.UI; using System.Collections.Generic; using UnityEngine; public class NodeTraversalExample : MonoBehaviour { // Parse-time traversal (on FigmaFile nodes) public void TraverseFigmaFile(FigmaFile file) { file.BuildHierarchy(); // Traverse entire document file.document.TraverseDfs(node => { // Process each node Debug.Log($"Node: {node.name} ({node.type})"); // Access node-specific properties if (node is FrameNode frame) { Debug.Log($" Frame size: {frame.size}"); Debug.Log($" Auto-layout: {frame.layoutMode}"); } else if (node is TextNode text) { Debug.Log($" Text: {text.characters}"); Debug.Log($" Font: {text.style?.fontFamily}"); } else if (node is InstanceNode instance) { Debug.Log($" Component ID: {instance.componentId}"); } return true; // Continue traversal }); // Filter by node type var textNodes = new List(); file.document.TraverseDfs(node => { textNodes.Add((TextNode)node); return true; }, NodeType.Text); Debug.Log($"Found {textNodes.Count} text nodes"); } // Runtime traversal (on imported FigmaNode hierarchy) public void TraverseImportedDesign(FigmaDesign design) { // Traverse all nodes in the design design.document.TraverseDfs(node => { Debug.Log($"Runtime Node: {node.nodeName} ({node.nodeType})"); return true; }); // Find nodes by condition var allButtons = new List(); design.document.TraverseDfs(node => { if (node.bindingKey?.Contains("Button") == true) { allButtons.Add(node); } return true; }); // Find nodes by tag design.document.TraverseDfs(node => { if (System.Array.IndexOf(node.tags, "interactive") >= 0) { Debug.Log($"Interactive node: {node.nodeName}"); } return true; }); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.