123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- namespace Ragdoll
- {
- public delegate void ResetDelegate(object value);
- [AttributeUsage(AttributeTargets.Field)]
- public class RdResetAttribute : Attribute
- {
- public object DefaultValue { get; set; }
- public RdResetAttribute(object defaultValue = null)
- {
- DefaultValue = defaultValue;
- }
- }
- public static class RdResetTool
- {
- public static void ResetAttribute(object obj)
- {
- var type = obj.GetType();
- foreach (var field in type.GetFields())
- {
- var resetAttribute = field.GetCustomAttributes(typeof(RdResetAttribute), true)
- as RdResetAttribute[];
- if (resetAttribute.Length == 0) continue;
- var defaultValue = resetAttribute[0].DefaultValue;
- Debug.Log("重置 " + field.Name);
- if (defaultValue == null)
- {
- Debug.Log("重置为默认值");
- if (field.FieldType == typeof(string)) // 字符串类型重置为null
- {
- field.SetValue(obj, null);
- }
- else if (field.FieldType == typeof(int) ||
- field.FieldType == typeof(float) ||
- field.FieldType == typeof(double) ||
- field.FieldType == typeof(long) ||
- field.FieldType == typeof(short) ||
- field.FieldType == typeof(byte) ||
- field.FieldType == typeof(uint) ||
- field.FieldType == typeof(ulong) ||
- field.FieldType == typeof(ushort) ||
- field.FieldType == typeof(sbyte))
- {
- field.SetValue(obj, 0); // 数值型重置为0
- }
- else if (field.FieldType == typeof(bool)) // 布尔类型重置为false
- {
- field.SetValue(obj, false);
- }
- else if (field.FieldType.IsArray) // 数组重置为空数组
- {
- field.SetValue(obj, Array.CreateInstance(field.FieldType.GetElementType(), 0));
- }
- else if (field.FieldType.IsGenericType &&
- field.FieldType.GetGenericTypeDefinition() == typeof(List<>)) // 列表重置为空列表
- {
- field.SetValue(obj, Activator.CreateInstance(field.FieldType));
- }
- else if (field.FieldType.IsGenericType &&
- field.FieldType.GetGenericTypeDefinition() == typeof(Dictionary<,>)) // 字典重置为空字典
- {
- field.SetValue(obj, Activator.CreateInstance(field.FieldType));
- }
- else // 其他类型重置为null
- {
- Debug.Log("未兼容的类型,重置为null");
- field.SetValue(obj, null);
- }
- }
- else
- {
- Debug.Log("重置为自定义默认值");
- field.SetValue(obj, defaultValue);
- }
- }
- }
- }
- }
|