using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Profiling; using System.Collections; public class MemoryManager : MonoBehaviour { public static MemoryManager Instance; [Header("Memory Check")] [SerializeField] private float checkInterval = 10f; [SerializeField] private long memoryThresholdMB = 300; [Header("Debug")] [SerializeField] private bool showLogs = true; private float timer; private bool isCleaning = false; void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } void OnEnable() { SceneManager.sceneLoaded += OnSceneLoaded; } void OnDisable() { SceneManager.sceneLoaded -= OnSceneLoaded; } void Update() { timer += Time.deltaTime; if (timer >= checkInterval) { CheckMemory(); timer = 0f; } } void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (showLogs) Debug.Log($"Scene loaded: {scene.name} - Cleaning memory"); CleanMemory(); } void CheckMemory() { long usedMemory = Profiler.GetTotalAllocatedMemoryLong() / (1024 * 1024); if (showLogs) Debug.Log($"Memory: {usedMemory}MB / Threshold: {memoryThresholdMB}MB"); if (usedMemory > memoryThresholdMB) { if (showLogs) Debug.Log($"Memory high - Cleaning"); CleanMemory(); } } // Appel via Instance public void CleanMemory() { if (!isCleaning) { StartCoroutine(CleanMemoryRoutine()); } } // Appel static direct public static void Clean() { if (Instance != null) { Instance.CleanMemory(); } } private IEnumerator CleanMemoryRoutine() { isCleaning = true; yield return Resources.UnloadUnusedAssets(); System.GC.Collect(); if (showLogs) { long afterClean = Profiler.GetTotalAllocatedMemoryLong() / (1024 * 1024); Debug.Log($"Memory after clean: {afterClean}MB"); } isCleaning = false; } }