Skip to content

Commit

Permalink
Fix: support when savedata is a dictionary
Browse files Browse the repository at this point in the history
Previously plugin savedata could have only been a class with fields and properties.
Now dictionaries are also supported.

For example:
ModSaves.RegisterSaveLoadGameData<Dictionary<string, SaveDataAdapter>>(
            "My mod GUID",
            OnSave,
            OnLoad
        );
  • Loading branch information
Falki-git committed Nov 25, 2023
1 parent 5e4aec8 commit 23c029c
Showing 1 changed file with 26 additions and 11 deletions.
37 changes: 26 additions & 11 deletions SpaceWarp.Core/InternalUtilities/InternalExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Reflection;
using System;
using UnityEngine;
using System.Collections;

namespace SpaceWarp.InternalUtilities;

Expand All @@ -14,22 +15,36 @@ internal static void Persist(this UnityObject obj)

internal static void CopyFieldAndPropertyDataFromSourceToTargetObject(object source, object target)
{
foreach (FieldInfo field in source.GetType().GetFields())
// check if it's a dictionary
if (source is IDictionary sourceDictionary && target is IDictionary targetDictionary)
{
object value = field.GetValue(source);

try
// copy dictionary items
foreach (DictionaryEntry entry in sourceDictionary)
{
field.SetValue(target, value);
targetDictionary[entry.Key] = entry.Value;
}
catch (FieldAccessException)
{ /* some fields are constants */ }
}

foreach (PropertyInfo property in source.GetType().GetProperties())
else
{
object value = property.GetValue(source);
property.SetValue(target, value);
// copy fields
foreach (FieldInfo field in source.GetType().GetFields())
{
object value = field.GetValue(source);

try
{
field.SetValue(target, value);
}
catch (FieldAccessException)
{ /* some fields are constants */ }
}

// copy properties
foreach (PropertyInfo property in source.GetType().GetProperties())
{
object value = property.GetValue(source);
property.SetValue(target, value);
}
}
}
}

0 comments on commit 23c029c

Please sign in to comment.