1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- namespace Ragdoll
- {
-
- [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,
- field.FieldType.GetElementType() == null
- ? null
- : 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);
- }
- }
- }
- }
- }
|