Skia for Unity

repository·main·Indexed 41 days ago

https://github.com/ammariqais/skiaforunity

A high-performance 2D graphics plugin for Unity integrating SkiaSharp and HarfBuzz. It provides advanced vector shape rendering via SkiaGraphic, sophisticated text handling with HB TextBlock and HB InputField, and Lottie animation support through SkottiePlayer. Features include RTL text support, rich text tags, a pre-bake system to convert vector elements into static PNG assets for optimization, and a text animator for sequential effects. Version 4.2.2.

Tokens
6.1K
Snippets
14
Records
27
Agent score
47%

What's inside Skia for Unity

  1. Apply text effects to HB_TEXTBlock

    main

    Enhance text appearance using the following Inspector settings on HB_TEXTBlock:

    • Outline: Set Outline Width > 0. Configure Outline Color (supports gradients) and Outline Blur.
    • Drop Shadow: Set Shadow Width > 0. Adjust Shadow Offset X/Y and Shadow Color.
    • Inner Glow: Set Inner Glow Width > 0 and choose an Inner Glow Color.
    • Color Gradient: Enable Color Gradient and set gradient colors, positions, and angle.
  2. Optimize performance with the Pre-Bake System

    main

    To eliminate SkiaSharp runtime costs, you can use the Pre-Bake system to convert vector elements into static assets.

    How it works:

    1. Select a SkiaGraphic or HB TextBlock in the Inspector.
    2. Click the Bake to PNG button.
    3. The system automatically converts the component to a RawImage or Image component and saves the result as a Sprite PNG.
    4. The baked element is automatically added to a shared SpriteAtlas to enable efficient draw call batching (e.g., 20 baked elements can be rendered in 1–2 draw calls).

    Key Details:

    • Nine-slice: SkiaGraphic solid fills support nine-slice, allowing you to resize baked elements without re-baking.
    • Unbake: You can click Unbake to instantly restore live SkiaSharp rendering.
    • Safety: Inspector properties are greyed out when an element is baked to prevent accidental edits.
  3. Install SkiaSharp for Unity via Package Manager

    main

    To install the plugin in your Unity project, use the Git URL method via the Package Manager:

    1. Open Unity and navigate to Window > Package Manager.
    2. Click the + button in the top-left corner.
    3. Select Add package from git URL....
    4. Enter the following URL:

    https://github.com/ammariqais/SkiaForUnity.git?path=SkiaUnity/Assets/SkiaSharp

    1. Click Add to import the package.
    https://github.com/ammariqais/SkiaForUnity.git?path=SkiaUnity/Assets/SkiaSharp
  4. Animate text with HBTextAnimator

    main

    The HBTextAnimator component allows you to create sequential animation steps for HB_TEXTBlock objects.

    Setup

    1. Select an HB_TEXTBlock GameObject.
    2. Add the HBTextAnimator component.

    Animation Structure

    Animations consist of one or more steps played sequentially. Each step has a Name, Duration, Delay, and Ease Curve.

    Available Effects per Step

    • Typewriter: Reveals text character by character.
    • Fade: Transitions from From alpha to To alpha.
    • Color Lerp: Transitions from From color to To color.
    • Scale: Transitions from From scale (Vector3) to To scale.
    • Slide: Slides in from an Offset (Vector2).
    • Shake: Random offset with decaying Intensity.
    • Gradient Angle: Animates Start angle to End angle.
    • Outline Pulse: Animates From width to To width.
    • Shadow Animate: Animates From offset (Vector2) to To offset.
    • Font Size: Animates From size to To size.
    • Letter Spacing: Animates From spacing to To spacing.

    Editor Preview

    Use the Preview button in the Inspector to test animations without entering Play Mode. A progress bar shows the current step.

    using SkiaSharp.Unity.HB;
    using UnityEngine;
    
    public class AnimatorExample : MonoBehaviour {
        [SerializeField] HBTextAnimator animator;
    
        void Start() {
            // Auto-play is on by default, or call manually:
            animator.Play();
    
            animator.onStepComplete.AddListener(stepIndex => {
                Debug.Log("Step " + stepIndex + " completed");
            });
    
            animator.onComplete.AddListener(() => {
                Debug.Log("All steps completed");
            });
        }
    
        public void StopAnimation() {
            animator.Stop(); // Restores original state
        }
    }
  5. Use SkiaGraphic for vector shapes

    main

    The SkiaGraphic component allows you to render vector shapes directly on the Unity Canvas without writing code. You can create a new instance by right-clicking in the Hierarchy: GameObject > Skia UI (Canvas) > Skia Graphic.

    Supported Features:

    • Shapes: Rectangle, RoundedRect (with per-corner radii), Circle, and Ellipse.
    • Fills: Solid color, LinearGradient, RadialGradient, SweepGradient, and Image (with Stretch/Fit/Fill/Tile modes).
    • Strokes: Solid or gradient strokes with configurable width and dashed options.
    • Shadows: Supports both Drop Shadow and Inner Shadow (offset, blur, and color).
    • Optimization: Includes a Resolution Scale setting to improve performance on mobile devices.
  6. Render text with HB_TEXTBlock

    main

    Use the HB_TEXTBlock component for high-quality text rendering powered by HarfBuzz.

    Setup

    1. Create the object: GameObject > Skia UI (Canvas) > HB TextBlock.
    2. Configure text: Set the Text field, Font Size, Font Color, and Alignment in the Inspector.

    Using Custom Fonts

    1. Import a .ttf or .otf file into your project.
    2. Create a font asset: Right-click the font file and select Create > HBFontData.
    3. Assign the font: Drag the HBFontData asset onto the Font field of the HB_TEXTBlock component. (Note: Dragging a .ttf/.otf file directly onto the field will automatically create an HBFontData asset).

    Font Fallbacks

    For multi-language support (e.g., mixing Latin and Arabic), add additional font assets to the Fallback Fonts array. HarfBuzz will automatically select the correct font for each character.

    using SkiaSharp.Unity.HB;
    using UnityEngine;
    
    public class TextExample : MonoBehaviour {
        [SerializeField] HB_TEXTBlock hbText;
    
        void Start() {
            hbText.text = "Hello World";
            hbText.FontSize = 32;
            hbText.FontColor = Color.white;
            hbText.Bold = true;
    
            // Listen for text changes
            hbText.onTextChanged.AddListener(() => Debug.Log("Text updated"));
        }
    }
  7. Create and script an HBInputField

    main

    The HBInputField provides a complete UI hierarchy for user text input.

    Setup

    1. Create the object: GameObject > Skia UI (Canvas) > HB InputField.

    Key Configuration Sections

    • Input Settings: Set Content Type (Standard, Integer, Decimal, Alphanumeric, Name, Email, Password), Line Type (SingleLine/MultiLine), and Character Limit.
    • Behavior: Enable Select All on Focus or Tab Navigation.
    • Mobile: Use Hide Mobile Input to hide the native iOS/Android overlay (recommended).
    • Caret: Customize Color, Blink Rate, and Width, or use Hide Caret to remove it.
    • Events: Use onValueChanged, onSubmit, onEndEdit, onFocus, and onUnfocus.

    Keyboard Shortcuts

    • Ctrl+A (Select all), Ctrl+C (Copy), Ctrl+V (Paste), Ctrl+X (Cut)
    • Ctrl+Left/Right (Jump by word)
    • Shift+Arrows (Extend selection)
    • Home / End (Move to start/end)
    • Tab / Shift+Tab (Navigate fields)
    • Double-click (Select word), Triple-click (Select all)
    using SkiaSharp.Unity.HB;
    using UnityEngine;
    
    public class InputExample : MonoBehaviour {
        [SerializeField] HBInputField inputField;
    
        void Start() {
            inputField.text = "Initial text";
    
            inputField.onValueChanged.AddListener(value => {
                Debug.Log("Changed: " + value);
            });
    
            inputField.onSubmit.AddListener(value => {
                Debug.Log("Submitted: " + value);
            });
    
            inputField.onFocus.AddListener(() => {
                Debug.Log("Input focused");
            });
        }
    }
  8. Install SkiaSharp for Unity

    main

    You can install SkiaSharp for Unity via the Unity Package Manager or by cloning the repository.

    Via Package Manager

    1. Open Unity and navigate to Window > Package Manager.
    2. Click the + button and select Add package from git URL.
    3. Enter the following URL:

    https://github.com/ammariqais/SkiaForUnity.git?path=SkiaUnity/Assets/SkiaSharp

    iOS Setup

    If building for iOS, you must manually add the following symbols to your Scripting Define Symbols:

    • __UNIFIED__
    • __IOS__

    To do this, go to Edit > Project Settings > Player > iOS tab, and add them under Other Settings > Scripting Define Symbols.

    https://github.com/ammariqais/SkiaForUnity.git?path=SkiaUnity/Assets/SkiaSharp
  9. Configure iOS Support for SkiaSharp for Unity

    main

    If you are targeting iOS, you must manually add specific scripting define symbols to ensure the library functions correctly:

    1. Go to Edit > Project Settings > Player.
    2. Select the iOS platform.
    3. Locate the Other Settings section.
    4. In the Scripting Define Symbols field, add the following symbols:
      • __UNIFIED__
      • __IOS__
  10. Play and control Lottie animations with SkottiePlayer

    main

    The SkottiePlayer class provides functionality to load, play, and control Lottie animations within Unity. You can manage animation states, retrieve playback metadata like FPS and duration, and respond to animation completion via events.

    Basic Usage

    To use SkottiePlayer, reference it in your script using [SerializeField] and call SetState and PlayAnimation to control the playback flow.

    [SerializeField]
    SkottiePlayer skottiePlayer;
    
    void Start() {
        // Set the desired animation state
        skottiePlayer.SetState("YourStateName");
    
        // Start playing the animation
        skottiePlayer.PlayAnimation();
    }
  11. Play Skottie animations with SkottiePlayer

    main

    To display Lottie animations in Unity using the SkottiePlayer component, follow these setup steps:

    1. Create a UI element: In your Unity scene, create a RawImage (Right-click Hierarchy > UI > Raw Image).
    2. Attach the component: Select the RawImage and add the SkottiePlayer component via the Inspector.
    3. Assign JSON data: Drag and drop your Lottie animation JSON file into the lottieFile field (labeled 'Animation Json File' in the Inspector) of the SkottiePlayer component.
    4. Control via script: Use SetState(string stateName) to define the animation state and PlayAnimation() to begin playback.
    [SerializeField]
    SkottiePlayer skottiePlayer;
    
    void Start() {
        // Set the desired animation state
        skottiePlayer.SetState("YourStateName");
    
        // Start playing the animation
        skottiePlayer.PlayAnimation();
    }