Passing data from SwiftUI to Unity

I’m trying to set up some SwiftUI sliders to modify Unity properties. I feel like I have a good handle on sending data from Unity to SwiftUI (@DanMillerU3D 's linkedIn post really helped) but I’m stuck on how to get values back from SwiftUI to Unity. I think I’m fine on the C# side, but I’m not sure how to create my own delegate/callback like the SwiftUISamplePlugin CallbackDelegateType/CallCSharpCallback that receives types of data other that strings.

This is the bit I’m most confused about, when trying to create my own:

typealias CallbackDelegateType = @convention(c) (UnsafePointer<CChar>) -> Void

var sCallbackDelegate: CallbackDelegateType? = nil

// Declared in C# as: static extern void SetNativeCallback(CallbackDelegate callback);
@_cdecl("SetNativeCallback")
func setNativeCallback(_ delegate: CallbackDelegateType)
{
    print("############ SET NATIVE CALLBACK")
    sCallbackDelegate = delegate
}

// This is a function for your own use from the enclosing Unity-VisionOS app, to call the delegate
// from your own windows/views (HelloWorldContentView uses this)
public func CallCSharpCallback(_ str: String)
{
    if (sCallbackDelegate == nil) {
        return
    }

    str.withCString {
        sCallbackDelegate!($0)
    }
}

Could anyone let me know how I can create a callback that receives for example a string, a float and an int parameters?
Thank you!!

Try:

typealias CallbackDelegateType = @convention(c) (UnsafePointer<CChar>, Float, Int32) -> Void

var sCallbackDelegate: CallbackDelegateType? = nil

@_cdecl("SetNativeCallback")
func setNativeCallback(_ delegate: CallbackDelegateType)
{
    sCallbackDelegate = delegate
}

public func CallCSharpCallback(_ str: String, _ floatValue: Float, _ intValue: Int32)
{
     if (callbackDelegate == nil) {
         return
     }
 
     str.withCString {
         callbackDelegate!($0, floatValue, intValue)
     }
}

On the C# side:

delegate void CallbackDelegate(string command, float floatValue, int intValue);

static void CallbackFromNative(string command, float floatValue, int intValue)
{
    // ...
}

C#'s int type is 32 bits, whereas Swift’s Int is 64 bits on 64 bit platforms (like visionOS), so you have to explicitly use Int32 in Swift.

ah so simple, thank you! still picking Swift up. will implement now and let you know how it goes

1 Like

thanks again @kapolka , got SwiftUI working great and I’m using it for most of my debug panels… here’s one example, to play with PBR values:
PBR SwiftUI panel

1 Like