diff --git a/OpenRA.Game/Scripting/ScriptObjectWrapper.cs b/OpenRA.Game/Scripting/ScriptObjectWrapper.cs index 7961eff8da..8d667ca3e3 100644 --- a/OpenRA.Game/Scripting/ScriptObjectWrapper.cs +++ b/OpenRA.Game/Scripting/ScriptObjectWrapper.cs @@ -24,6 +24,10 @@ namespace OpenRA.Scripting protected readonly ScriptContext Context; readonly Dictionary members = new Dictionary(); +#if !NET5_0_OR_GREATER + readonly List membersToRemove = new List(); +#endif + public ScriptObjectWrapper(ScriptContext context) { Context = context; @@ -63,9 +67,22 @@ namespace OpenRA.Scripting protected void Unbind(Type targetType) { +#if NET5_0_OR_GREATER + // NOTE: In newer versions of .NET modifying the collection by calling Remove while iterating over it is valid foreach (var m in members) if (targetType == m.Value.Target.GetType()) members.Remove(m.Key); +#else + // PERF: Re-use instead of allocating a new list on each unbind + membersToRemove.Clear(); + + foreach (var m in members) + if (targetType == m.Value.Target.GetType()) + membersToRemove.Add(m.Key); + + foreach (var m in membersToRemove) + members.Remove(m); +#endif } public bool ContainsKey(string key) { return members.ContainsKey(key); }