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.
- 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.
-
Clone repository
git clone https://github.com/bdeweygit/unity-swiftui.git cd unity-swiftui
-
Create build folder for Unity project
mkdir -p UnityProject/Builds/iOS
-
Open Unity project
- Use Unity Hub to open
UnityProject
directory. - Go to
File > Build Settings
. - In platform menu, select
iOS
and clickSwitch Platform
. - Click
Build
and chooseBuilds/iOS
folder you created earlier.
- Use Unity Hub to open
-
Open integration workspace
- Use Xcode to open
integration.xcworkspace
file.
- Use Xcode to open
-
Configure SwiftUI project
- Edit
UnitySwiftUI
target's signing settings with valid bundle identifier and signing team ID. - Switch to
UnitySwiftUI
scheme.
- Edit
-
Run app on a physical device
- Connect your physical device to Xcode.
- Build and run
UnitySwiftUI
scheme to your device.
- 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.
- 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.
- NativeStateManager.cs: Class for receiving and storing native state data.
- RootBehavior.cs: Script that renders content - a cube and a spotlight - reacting to state updates and touch events.
- NativeState.h, NativeState.m: Plugin enabling flow of state data from native Swift to Unity C#.
- UnityFramework.modulemap: Custom modulemap for plugin interoperability with Swift.
- PostProcessBuild.cs: Script automating integration of Unity generated Xcode project.
- 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.