Decompiled source of BONELABMemoryCleanup v0.1.0

Mods/BonelabMemoryCleanup.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BonelabMemoryCleanup;
using MelonLoader;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: MelonInfo(typeof(MemoryCleanupMod), "BONELAB Memory Cleanup", "0.1.0", "Steve Savage", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("BonelabMemoryCleanup")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("BonelabMemoryCleanup")]
[assembly: AssemblyTitle("BonelabMemoryCleanup")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace BonelabMemoryCleanup;

public class MemoryCleanupMod : MelonMod
{
	private bool cleanupRunning;

	public override void OnInitializeMelon()
	{
		((MelonBase)this).LoggerInstance.Msg("Loaded! Press F8 to request unused asset cleanup.");
	}

	public override void OnUpdate()
	{
		if (Input.GetKeyDown((KeyCode)289) && !cleanupRunning)
		{
			cleanupRunning = true;
			((MelonBase)this).LoggerInstance.Msg("Starting memory cleanup request...");
			MelonCoroutines.Start(CleanupRoutine());
		}
	}

	private IEnumerator CleanupRoutine()
	{
		long before = GC.GetTotalMemory(forceFullCollection: false);
		GC.Collect();
		GC.WaitForPendingFinalizers();
		GC.Collect();
		AsyncOperation operation = null;
		try
		{
			operation = Resources.UnloadUnusedAssets();
		}
		catch (Exception ex)
		{
			Exception ex2 = ex;
			((MelonBase)this).LoggerInstance.Error(ex2.ToString());
		}
		if (operation != null)
		{
			while (!operation.isDone)
			{
				yield return null;
			}
		}
		GC.Collect();
		long after = GC.GetTotalMemory(forceFullCollection: false);
		((MelonBase)this).LoggerInstance.Msg($"Managed memory before: {(double)before / 1048576.0:F1} MiB");
		((MelonBase)this).LoggerInstance.Msg($"Managed memory after: {(double)after / 1048576.0:F1} MiB");
		((MelonBase)this).LoggerInstance.Msg("Cleanup request finished. Active assets may remain loaded.");
		cleanupRunning = false;
	}
}