AutoConnectBLE.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using System.Reflection;
  6. public class AutoConnectBLE : MonoBehaviour
  7. {
  8. [SerializeField] string serverIP;
  9. GameObject obj_bluetoothHolder;
  10. void Start()
  11. {
  12. obj_bluetoothHolder = Instantiate(Resources.Load<GameObject>("Prefabs/BluetoothHolder"));
  13. SetServerIP();
  14. OpenBluetoothDebugView();
  15. StartCoroutine(ConnectBLE());
  16. }
  17. void SetServerIP()
  18. {
  19. BluetoothClient bluetoothClient = obj_bluetoothHolder.GetComponentInChildren<BluetoothClient>();
  20. FieldInfo field_serverIP = bluetoothClient.GetType().GetField("serverIP", BindingFlags.Instance | BindingFlags.NonPublic);
  21. field_serverIP.SetValue(bluetoothClient, serverIP);
  22. }
  23. void OpenBluetoothDebugView() {
  24. BluetoothHolder bluetoothHolder = obj_bluetoothHolder.GetComponent<BluetoothHolder>();
  25. FieldInfo field_debug = bluetoothHolder.GetType().GetField("debug", BindingFlags.Instance | BindingFlags.NonPublic);
  26. field_debug.SetValue(bluetoothHolder, true);
  27. //改变canvas渲染模式,让3d物体渲染在前面
  28. Canvas[] canvasArray = bluetoothHolder.transform.GetComponentsInChildren<Canvas>();
  29. foreach (var canvas in canvasArray)
  30. {
  31. canvas.renderMode = RenderMode.ScreenSpaceCamera;
  32. canvas.worldCamera = Camera.main;
  33. }
  34. StartCoroutine(ShowDebugView(bluetoothHolder));
  35. }
  36. IEnumerator ShowDebugView(BluetoothHolder bluetoothHolder) {
  37. yield return new WaitForSeconds(0.1f);
  38. bluetoothHolder.openDebug();
  39. }
  40. IEnumerator ConnectBLE()
  41. {
  42. yield return null;
  43. #if PLATFORM_ANDROID
  44. BluetoothAim bluetoothAim = obj_bluetoothHolder.GetComponentInChildren<BluetoothAim>();
  45. MethodInfo method_DoConnect = bluetoothAim.GetType().GetMethod("DoConnect");
  46. method_DoConnect.Invoke(bluetoothAim, new object[]{});
  47. #endif
  48. }
  49. }