/unity-swiftui

Primary LanguageSwiftMIT LicenseMIT

unity-swiftui

This is a reference project for those that want to use Unity as a Library in their SwiftUI iOS app. Unity's existing iOS documentation only demonstrates UAAL with UIKit/Objective-C projects and lacks illustrative examples of native-to-unity state flow, control of the Unity view, and automated integration of Unity's build output.

Screen recording

Requirements

  • Physical device with iOS 17.5 or later.
  • Unity Editor 2022.3.36f1 - latest LTS at time of this writing - with iOS build support installed in Unity Hub.

Instructions

  1. Clone repository

    git clone https://github.com/bdeweygit/unity-swiftui.git
    cd unity-swiftui
  2. Create build folder for Unity project

    mkdir -p UnityProject/Builds/iOS
  3. Open Unity project

    • Use Unity Hub to open UnityProject directory.
    • Go to File > Build Settings.
    • In platform menu, select iOS and click Switch Platform.
    • Click Build and choose Builds/iOS folder you created earlier.
  4. Open integration workspace

    • Use Xcode to open integration.xcworkspace file.
  5. Configure SwiftUI project

    • Edit UnitySwiftUI target's signing settings with valid bundle identifier and signing team ID.
    • Switch to UnitySwiftUI scheme.
  6. Run app on a physical device

    • Connect your physical device to Xcode.
    • Build and run UnitySwiftUI scheme to your device.

Key features

  • Control of Unity view as a SwiftUI element that can be repositioned and resized. Unity's documentation says "Unity as a Library only supports full-screen rendering, and doesn’t support rendering on part of the screen." We have fixed this limitation.
  • Touches and gestures on Unity view are processed within Unity.
  • Restarting the Unity player.
  • State data is sent from native Swift to Unity C# as a struct with members including string, boolean, floating point, integer, and MTLTexture types.

Key files

SwiftUI Project

  • Unity.swift: Class for controlling Unity framework and native-to-unity state flow.
  • ContentView.swift: UI demonstrating Unity view as a SwiftUI element and controls for layout and state.

Unity Project

Known issues

  • After building Unity project, Xcode workspace may not always reflect latest files and be unable to build. Close and reopen workspace to fix this bad state.
  • When running while attached to Xcode, there may be some noticeable delay between device orientation change and UI layout. There should be no such delay when running detached.