// Resources.UnloadUnusedAssets doesn’t work in Coroutine.
using System;
using System.Collections;
using UnityEditor;
using UnityEngine;
public class TestMaterialUnload : MonoBehaviour
{
private Renderer renderer1;
private Action action;
void Start()
{
renderer1 = GameObject.CreatePrimitive(PrimitiveType.Cube).GetComponent<Renderer>();
UnLoad();
UnLoadImmediate();
StartCoroutine(UnLoadCoroutine());
}
void Update()
{
action?.Invoke();
}
private void UnLoad()
{
var material = Material.Instantiate(renderer1.sharedMaterial);
Debug.Log("UnLoad Before: " + material); // Standard(Clone) (UnityEngine.Material)
var a = Resources.UnloadUnusedAssets();
a.completed += (op) =>
{
Debug.Log("UnLoad After: " + material); // null
};
}
private IEnumerator UnLoadCoroutine()
{
var material = Material.Instantiate(renderer1.sharedMaterial);
Debug.Log("UnLoadCoroutine Before: " + material); // Standard(Clone) (UnityEngine.Material)
var a = Resources.UnloadUnusedAssets();
a.completed += (op) =>
{
Debug.Log("UnLoadCoroutine After completed: " + material); // Standard(Clone) (UnityEngine.Material)
};
while (!a.isDone)
{
yield return null;
}
Debug.LogWarning("UnLoadCoroutine After: " + material); // Standard(Clone) (UnityEngine.Material)
action = () => { Debug.LogWarning("UnLoadCoroutine action: " + material); }; // Standard(Clone) (UnityEngine.Material)
action();
}
private void UnLoadImmediate()
{
var material = Material.Instantiate(renderer1.sharedMaterial);
Debug.Log("UnLoadImmediate3 Before: " + material); // Standard(Clone) (UnityEngine.Material)
EditorUtility.UnloadUnusedAssetsImmediate();
Debug.Log("UnLoadImmediate3 After: " + material); // null
}
}