Exemplo n.º 1
0
    public static BluetoothDeviceScript Initialize(bool asCentral, bool asPeripheral, Action action, Action <string> errorAction)
    {
        bluetoothDeviceScript = null;

#if UNITY_2018_3_OR_NEWER
#if UNITY_ANDROID
        if (!Permission.HasUserAuthorizedPermission(Permission.FineLocation))
        {
            Permission.RequestUserPermission(Permission.FineLocation);
        }
#endif
#endif

        GameObject bluetoothLEReceiver = GameObject.Find("BluetoothLEReceiver");
        if (bluetoothLEReceiver == null)
        {
            bluetoothLEReceiver = new GameObject("BluetoothLEReceiver");
        }

        if (bluetoothLEReceiver != null)
        {
            bluetoothDeviceScript = bluetoothLEReceiver.GetComponent <BluetoothDeviceScript> ();
            if (bluetoothDeviceScript == null)
            {
                bluetoothDeviceScript = bluetoothLEReceiver.AddComponent <BluetoothDeviceScript> ();
            }

            if (bluetoothDeviceScript != null)
            {
                bluetoothDeviceScript.InitializedAction = action;
                bluetoothDeviceScript.ErrorAction       = errorAction;
            }
        }

        GameObject.DontDestroyOnLoad(bluetoothLEReceiver);

#if EXPERIMENTAL_MACOS_EDITOR && (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX)
        ConnectUnitySendMessageCallback((objectName, commandName, commandData) => {
            string name    = Marshal.PtrToStringAuto(objectName);
            string command = Marshal.PtrToStringAuto(commandName);
            string data    = Marshal.PtrToStringAuto(commandData);

            GameObject foundObject = GameObject.Find(name);
            if (foundObject != null)
            {
                foundObject.SendMessage(command, data);
            }
        });

        BluetoothLEHardwareInterface.OSXBluetoothLEInitialize(asCentral, asPeripheral);
#else
        if (Application.isEditor)
        {
            if (bluetoothDeviceScript != null)
            {
                bluetoothDeviceScript.SendMessage("OnBluetoothMessage", "Initialized");
            }
        }
        else
        {
#if UNITY_IOS || UNITY_TVOS
            _iOSBluetoothLEInitialize(asCentral, asPeripheral);
#elif UNITY_ANDROID
            if (_android == null)
            {
                AndroidJavaClass javaClass = new AndroidJavaClass("com.shatalmic.unityandroidbluetoothlelib.UnityBluetoothLE");
                _android = javaClass.CallStatic <AndroidJavaObject> ("getInstance");
            }

            if (_android != null)
            {
                _android.Call("androidBluetoothInitialize", asCentral, asPeripheral);
            }
#endif
        }
#endif

        return(bluetoothDeviceScript);
    }