ClassEnumerator.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * @brief enumerator all types for this app
  3. */
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Reflection;
  7. using System;
  8. using UnityEngine;
  9. public class ClassEnumerator
  10. {
  11. protected List<Type> Results = new List<Type>();
  12. public List<Type> results { get { return Results; } }
  13. private Type AttributeType;
  14. private Type InterfaceType;
  15. public ClassEnumerator(
  16. Type InAttributeType,
  17. Type InInterfaceType,
  18. Assembly InAssembly,
  19. bool bIgnoreAbstract = true,
  20. bool bInheritAttribute = false,
  21. bool bShouldCrossAssembly = false
  22. )
  23. {
  24. AttributeType = InAttributeType;
  25. InterfaceType = InInterfaceType;
  26. try
  27. {
  28. if (bShouldCrossAssembly)
  29. {
  30. Assembly[] Assemblys = AppDomain.CurrentDomain.GetAssemblies();
  31. if( Assemblys != null )
  32. {
  33. for( int i= 0; i<Assemblys.Length; ++i)
  34. {
  35. var a = Assemblys[i];
  36. CheckInAssembly(a, bIgnoreAbstract, bInheritAttribute);
  37. }
  38. }
  39. }
  40. else
  41. {
  42. CheckInAssembly(InAssembly, bIgnoreAbstract, bInheritAttribute);
  43. }
  44. }
  45. catch (Exception e)
  46. {
  47. Debug.LogError("Error in enumerate classes :" + e.Message);
  48. }
  49. }
  50. protected void CheckInAssembly(
  51. Assembly InAssembly,
  52. bool bInIgnoreAbstract,
  53. bool bInInheritAttribute
  54. )
  55. {
  56. Type[] Types = InAssembly.GetTypes();
  57. if( Types != null)
  58. {
  59. for (int i = 0; i < Types.Length; ++i )
  60. {
  61. var t = Types[i];
  62. // test if it is implement from this interface
  63. if ( InterfaceType == null || InterfaceType.IsAssignableFrom(t))
  64. {
  65. // check if it is abstract
  66. if (!bInIgnoreAbstract || (bInIgnoreAbstract && !t.IsAbstract))
  67. {
  68. // check if it have this attribute
  69. if (t.GetCustomAttributes(AttributeType, bInInheritAttribute).Length > 0)
  70. {
  71. Results.Add(t);
  72. // Debug.Log("Found Type:" + t.FullName + " : " + a.GetName());
  73. }
  74. }
  75. }
  76. }
  77. }
  78. }
  79. }