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