VoiceServiceReference.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. using System;
  9. using UnityEngine;
  10. #if UNITY_EDITOR
  11. using UnityEditor;
  12. #endif
  13. namespace Meta.WitAi.Utilities
  14. {
  15. [Serializable]
  16. public struct VoiceServiceReference
  17. {
  18. [SerializeField] internal VoiceService voiceService;
  19. public VoiceService VoiceService
  20. {
  21. get
  22. {
  23. if (!voiceService)
  24. {
  25. VoiceService[] services = Resources.FindObjectsOfTypeAll<VoiceService>();
  26. if (services != null)
  27. {
  28. // Set as first instance that isn't a prefab
  29. voiceService = Array.Find(services, (o) => o.gameObject.scene.rootCount != 0);
  30. }
  31. }
  32. return voiceService;
  33. }
  34. }
  35. }
  36. #if UNITY_EDITOR
  37. [CustomPropertyDrawer(typeof(VoiceServiceReference))]
  38. public class VoiceServiceReferenceDrawer : PropertyDrawer
  39. {
  40. public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
  41. {
  42. return EditorGUIUtility.singleLineHeight;
  43. }
  44. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  45. {
  46. var refProp = property.FindPropertyRelative("voiceService");
  47. var reference = refProp.objectReferenceValue as VoiceService;
  48. var voiceServices = GameObject.FindObjectsOfType<VoiceService>();
  49. var voiceServiceNames = new string[voiceServices.Length + 1];
  50. int index = 0;
  51. voiceServiceNames[0] = "Autodetect";
  52. if (voiceServices.Length == 1)
  53. {
  54. voiceServiceNames[0] = $"{voiceServiceNames[0]} - {voiceServices[0].name}";
  55. }
  56. for (int i = 0; i < voiceServices.Length; i++)
  57. {
  58. voiceServiceNames[i + 1] = voiceServices[i].name;
  59. if (voiceServices[i] == reference)
  60. {
  61. index = i + 1;
  62. }
  63. }
  64. EditorGUI.BeginProperty(position, label, property);
  65. var updatedIndex = EditorGUI.Popup(position, index, voiceServiceNames);
  66. if (index != updatedIndex)
  67. {
  68. if (updatedIndex > 0)
  69. {
  70. refProp.objectReferenceValue = voiceServices[updatedIndex - 1];
  71. }
  72. else
  73. {
  74. refProp.objectReferenceValue = null;
  75. }
  76. property.serializedObject.ApplyModifiedProperties();
  77. }
  78. EditorGUI.EndProperty();
  79. }
  80. }
  81. #endif
  82. }