SyncObjectCollectionsDrawer.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // helper class for NetworkBehaviourInspector to draw all enumerable SyncObjects
  2. // (SyncList/Set/Dictionary)
  3. // 'SyncObjectCollectionsDrawer' is a nicer name than 'IEnumerableSyncObjectsDrawer'
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Reflection;
  7. using UnityEditor;
  8. namespace Mirror
  9. {
  10. class SyncObjectCollectionField
  11. {
  12. public bool visible;
  13. public readonly FieldInfo field;
  14. public readonly string label;
  15. public SyncObjectCollectionField(FieldInfo field)
  16. {
  17. this.field = field;
  18. visible = false;
  19. label = $"{field.Name} [{field.FieldType.Name}]";
  20. }
  21. }
  22. public class SyncObjectCollectionsDrawer
  23. {
  24. readonly UnityEngine.Object targetObject;
  25. readonly List<SyncObjectCollectionField> syncObjectCollectionFields;
  26. public SyncObjectCollectionsDrawer(UnityEngine.Object targetObject)
  27. {
  28. this.targetObject = targetObject;
  29. syncObjectCollectionFields = new List<SyncObjectCollectionField>();
  30. foreach (FieldInfo field in InspectorHelper.GetAllFields(targetObject.GetType(), typeof(NetworkBehaviour)))
  31. {
  32. // only draw SyncObjects that are IEnumerable (SyncList/Set/Dictionary)
  33. if (field.IsVisibleSyncObject() &&
  34. field.ImplementsInterface<SyncObject>() &&
  35. field.ImplementsInterface<IEnumerable>())
  36. {
  37. syncObjectCollectionFields.Add(new SyncObjectCollectionField(field));
  38. }
  39. }
  40. }
  41. public void Draw()
  42. {
  43. if (syncObjectCollectionFields.Count == 0) { return; }
  44. EditorGUILayout.Space();
  45. EditorGUILayout.LabelField("Sync Collections", EditorStyles.boldLabel);
  46. for (int i = 0; i < syncObjectCollectionFields.Count; i++)
  47. {
  48. DrawSyncObjectCollection(syncObjectCollectionFields[i]);
  49. }
  50. }
  51. void DrawSyncObjectCollection(SyncObjectCollectionField syncObjectCollectionField)
  52. {
  53. syncObjectCollectionField.visible = EditorGUILayout.Foldout(syncObjectCollectionField.visible, syncObjectCollectionField.label);
  54. if (syncObjectCollectionField.visible)
  55. {
  56. using (new EditorGUI.IndentLevelScope())
  57. {
  58. object fieldValue = syncObjectCollectionField.field.GetValue(targetObject);
  59. if (fieldValue is IEnumerable syncObject)
  60. {
  61. int index = 0;
  62. foreach (object item in syncObject)
  63. {
  64. string itemValue = item != null ? item.ToString() : "NULL";
  65. string itemLabel = $"Element {index}";
  66. EditorGUILayout.LabelField(itemLabel, itemValue);
  67. index++;
  68. }
  69. }
  70. }
  71. }
  72. }
  73. }
  74. }