using System; using System.Collections.Generic; using BindingFlags = System.Reflection.BindingFlags; using UnityEngine; public static class Extensions { public enum LevelObjectType { GameObject, Tile } public static bool Approximately(this Vector3 vect, Vector3 other) { return Mathf.Approximately(Vector3.Distance(vect, other), 0); } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class LevelSerializeAttribute : Attribute { } /// /// turns an object into a serializable dictionary /// /// /// /// public static Dictionary ToDictionary(this T obj) where T : ILevelObject { var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; var toReturn = new Dictionary(); var type = obj.GetType(); foreach (var field in type.GetFields(flags)) { if (!Attribute.IsDefined(field, typeof(LevelSerializeAttribute))) continue; toReturn[field.Name] = field.GetValue(obj); } foreach (var property in type.GetProperties(flags)) { if (!Attribute.IsDefined(property, typeof(LevelSerializeAttribute))) continue; toReturn[property.Name] = property.GetValue(obj); } if (obj is LevelObject) toReturn[nameof(LevelObjectType)] = LevelObjectType.GameObject; else toReturn[nameof(LevelObjectType)] = LevelObjectType.Tile; return toReturn; } }