【Unity3D】Release of invalid GC handle. When Unity tries to access objects in the application domain that have been unloaded

Unity error

Release of invalid GC handle. The handle is from previous domain. The release operation is skipped.
Insert image description here

answer

This error usually occurs when trying to access or operate an object in an Application Domain that has been unloaded. In .NET, an application domain is an isolation boundary that allows multiple applications to run in the same process without interfering with each other. When an application domain is unloaded, all objects in it are cleaned up, including garbage collection handles.

In Unity, when you switch from one scene to another, or reload the current scene, the current application domain is unloaded and a new one is loaded. This error will occur if during this process you try to access objects in an application domain that has been uninstalled.

The solution to this problem is usually to ensure that all resources are properly cleaned up and released before unloading the application domain. For example, if you access an object in an application domain that has been unloaded in a MonoBehaviour's OnDestroy method, you may need to add a check in the OnDestroy method to avoid this situation. For example:

void OnDestroy() 
{
    
    
    if (gameObject != null) 
    {
    
    
        // 释放资源
    }
}

In addition, if you use C# events or delegates, you need to make sure to unsubscribe from these events or delegates before the object is destroyed, otherwise this error may also occur. For example:

void OnEnable() 
{
    
    
    someEvent += SomeEventHandler;
}

void OnDisable() 
{
    
    
    someEvent -= SomeEventHandler;
}

The above code ensures that when the object is disabled or destroyed, it no longer subscribes tosomeEvent events, thus avoiding attempts to access invalid event handlers after the application domain has been unloaded device.

Guess you like

Origin blog.csdn.net/weixin_41932970/article/details/134271809