Bluetooth RFCOMM with Unity? Windows Store App

Hi, a week or so ago I posted a question on how to have my game receive a BLE advertisement (here).

That worked well, but I’ve been thinking it would be better for me to pair a Bluetooth device directly, rather than just picking up a nearby BLE advertisement.

Similar to last time, I found a great Universal Windows Store app that demonstrates pairing a Bluetooth device and sending / receiving data back and forth (I only really care about receiving data). I tested it out on the Hololens and it works great. The example can be found on GitHub here, and a direct link to its MainPage code here.

Now, the tricky part is converting it for use in Unity. I can convert it to use Unity UI elements, but I don’t know how to have Unity handle the async / await operations, or if it is even possible. Wrapping most of the code in #if NETFX_CORE statements allows me to build the project, but it often crashes.

Specifically, I keep getting the error:
get_isActiveAndEnabled can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don’t use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

Typically i get that error as soon as I try to receive data, and the app crashes. Sometimes it occurs when I attempt to pair the Bluetooth device. Most of the time the Bluetooth device seems to pair, although I have to go to Settings > Privacy > Other Devices and allow my app to use it, after it has failed once. The app frequently gets frozen after paring though.

Any ideas? From what I’ve seen I have to do some sort of Thread management. My code is pretty similar to the example, but I could post it if needed.

Thanks

This error basically means you’re trying to access Unity APIs from a thread that’s not a Unity’s main thread. That probably happens after “await …” call, as that will put you on another thread after that line.

Ah, OK. So as long as I don’t try to access Unity APIs at that time it should be fine?

It looks like I can consistently transfer a string using that approach. Instead of trying to update the canvas right away I have a separate button and method used to check the string value, and update the display. This requires me to manually click the button though.

What is a good way to avoid having to click the button? Should I just constantly check in Update for a change in the string?

Thanks!

You can use this API to invoke code on Unity’s main thread:

Just make sure to pass “false” as the second parameter to avoid deadlocks.

That worked great!

Thanks for your help.