RdResetAttribute.cs 3.5 KB

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