SwiftUI and Unity communication


I am building a window with the SwiftUI sample from polyspatial. It works nice and everything and now I am trying to pass data, for example the window containing the amount of buttons I set on Unity.

I managed to send data from Unity to the plugin (SwiftUISamplePlugin) and there I can print and works correctly. But I’m unable to find a way to send that data to the InjectedScene and later to ContentView.

Anyone has an idea or know how this can be achieved?


How did you manage to send data from Unity to the plugin?

There are a few ways to accomplish this. I’ll try to describe one setup (not sure this is the best way but seemed to work) at a high level and if I find some time I can put together a small sample.

have a variable and native methods in SwiftUISamplePlugin that set and return a value

var bar: Bool

func setBar(_ bool: Bool)
     bar = bool
public func GetFoo() -> Bool {
    return bar

In the InjectedScene you can create an separate ObservableObject class to hold your data

class FooData: ObservableObject {
  @Published var bar: Bool = true

in HelloWorldContentView make sure you have a state object of your Observable Object type

@StateObject var fooData = FooData()

Then in the content view you can set and read values like this

func InitValues(data: FooData) {
    data.bar = GetFoo()

in Unity SwiftUIDriver.cs

static extern void SetBar(bool foo);

static void SetBar(bool foo) {}

Then in your gameplay script you set the value with a native method

var fooValue = true

Hope this helps!

1 Like

Thank you for the response Dan.
I will try it out.

Hi Dan, sry to ask you in this post cause I was not allow to create new topic in visionOS currently. The template can package swift script after we build the xcode project. But when we try to use swiftUI in other new vision projects, I got this error when building “Error building Player: BuildFailedException: File Libraries/ARM64/Assets/Script/UI/SwiftUI/ARRoomInjectedScene.swift is expected to be in the generated Xcode project, but it is missing”

It is solved after disabled and enabling again the visionos platform setting of the swift script