There and Back Again - Unity to Swift communication

There was some feedback in learning about starting a SharePlay session, about how to do it if your app was made using Unity.

You need a C# class that can send messages to swift. I call mine SwiftBridge:

public class SwiftBridge
{
[DllImport("__Internal")]
    private static extern void StartSharePlaySession();

public static void StartSharePlay()
    {
        try
        {
            StartSharePlaySession();
        }
        catch (Exception e)
        {
            D.Log(e.ToString());
        }
    }
}

In the Plugins folder I add SharePlayBridge.swift. But it's best to name it something relevant to your needs.

//Received messages from function above
@objc public class SharePlayBridge: NSObject {
    @_cdecl("StartSharePlaySession")
    public func StartSharePlaySession() {
        SharePlayBridge.startSession()
    }
}

@_silgen_name("UnitySendMessage")
func UnitySendMessage(_ obj: UnsafePointer<CChar>, _ method: UnsafePointer<CChar>, _ msg: UnsafePointer<CChar>)

//Sends messages to Unity
@objc public class SwiftUnityBridge: NSObject {
    @objc public static func sendToUnity(gameObject: String, method: String, message: String) {
        gameObject.withCString { gameObjectPtr in
            method.withCString { methodPtr in
                message.withCString { messagePtr in
                    UnitySendMessage(gameObjectPtr, methodPtr, messagePtr)
                }
            }
        }
    }
}

and then call this function whenever you want to send messages back to Unity.

SwiftUnityBridge.sendToUnity(gameObject: "[GAMEOBJECT_NAME]", method: "[METHOD_NAME_IN_MONOBEHAVIOUR_ON_GAMEOBJECT]", message: "[MESSAGE]")

If you are digging in to visionOS development, I can highly recommend the Step into Vision website and group. That's where a lot of the discussion for these posts originates from, so you can get sneak peeks, by heading over there.

Subscribe to Hands on Vision

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe