RdResetAttribute.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace Ragdoll
  5. {
  6. public delegate void ResetDelegate(object value);
  7. [AttributeUsage(AttributeTargets.Field)]
  8. public class RdResetAttribute : Attribute
  9. {
  10. public object DefaultValue { get; set; }
  11. public RdResetAttribute(object defaultValue = null)
  12. {
  13. DefaultValue = defaultValue;
  14. }
  15. }
  16. public static class RdResetTool
  17. {
  18. public static void ResetAttribute(object obj)
  19. {
  20. var type = obj.GetType();
  21. foreach (var field in type.GetFields())
  22. {
  23. var resetAttribute = field.GetCustomAttributes(typeof(RdResetAttribute), true)
  24. as RdResetAttribute[];
  25. if (resetAttribute.Length == 0) continue;
  26. var defaultValue = resetAttribute[0].DefaultValue;
  27. Debug.Log("重置 " + field.Name);
  28. if (defaultValue == null)
  29. {
  30. Debug.Log("重置为默认值");
  31. if (field.FieldType == typeof(string)) // 字符串类型重置为null
  32. {
  33. field.SetValue(obj, null);
  34. }
  35. else if (field.FieldType == typeof(int) ||
  36. field.FieldType == typeof(float) ||
  37. field.FieldType == typeof(double) ||
  38. field.FieldType == typeof(long) ||
  39. field.FieldType == typeof(short) ||
  40. field.FieldType == typeof(byte) ||
  41. field.FieldType == typeof(uint) ||
  42. field.FieldType == typeof(ulong) ||
  43. field.FieldType == typeof(ushort) ||
  44. field.FieldType == typeof(sbyte))
  45. {
  46. field.SetValue(obj, 0); // 数值型重置为0
  47. }
  48. else if (field.FieldType == typeof(bool)) // 布尔类型重置为false
  49. {
  50. field.SetValue(obj, false);
  51. }
  52. else if (field.FieldType.IsArray) // 数组重置为空数组
  53. {
  54. field.SetValue(obj, Array.CreateInstance(field.FieldType.GetElementType(), 0));
  55. }
  56. else if (field.FieldType.IsGenericType &&
  57. field.FieldType.GetGenericTypeDefinition() == typeof(List<>)) // 列表重置为空列表
  58. {
  59. field.SetValue(obj, Activator.CreateInstance(field.FieldType));
  60. }
  61. else if (field.FieldType.IsGenericType &&
  62. field.FieldType.GetGenericTypeDefinition() == typeof(Dictionary<,>)) // 字典重置为空字典
  63. {
  64. field.SetValue(obj, Activator.CreateInstance(field.FieldType));
  65. }
  66. else // 其他类型重置为null
  67. {
  68. Debug.Log("未兼容的类型,重置为null");
  69. field.SetValue(obj, null);
  70. }
  71. }
  72. else
  73. {
  74. Debug.Log("重置为自定义默认值");
  75. field.SetValue(obj, defaultValue);
  76. }
  77. }
  78. }
  79. }
  80. }