Felix Boucher 4fbce56853 travail sur le save et le load
problème : pas de moyen de sauvegarder et de charger les niveaux entamés

solution : fonctions save et load dans le LevelManager
2023-05-27 20:38:43 -04:00

53 lines
1.8 KiB
C#

using System;
using System.Collections.Generic;
using BindingFlags = System.Reflection.BindingFlags;
using UnityEngine;
public static class Extensions
{
public static T GetComponentInChildren<T>(this Component obj, string name) where T : Component
{
foreach (var comp in obj.GetComponentsInChildren<T>())
{
if (comp.name == name) return comp;
}
return null;
}
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 { }
/// <summary>
/// turns an object into a serializable dictionary
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static Dictionary<string, object> ToDictionary<T>(this T obj) where T : ILevelObject
{
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
var toReturn = new Dictionary<string, object>();
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;
}
}