cesium-unity icon indicating copy to clipboard operation
cesium-unity copied to clipboard

Crashes in `UnityPrepareRendererResources` when unloading and reloading scenes

Open azrogers opened this issue 9 months ago • 1 comments

A user reported on our forums that there were crash issues in Cesium for Unity when unloading and reloading the same scene. I fixed one such issue in #560, but it turns out there's others. I've noticed crashes in UnityPrepareRendererResources::free as well as additional crashes in prepareInLoadThread, particularly while populateMeshDataArray is running in the worker thread.

These crashes seem to come down to the fact that managed resources can be destroyed by Unity while we're in the process of using them on the worker thread. Unfortunately, unlike the GameObject issue which could be solved by a simple null check, I can't think of a way to solve these issues without just giving up on running things in the worker thread entirely. We can't do a null check against a managed array, for example.

azrogers avatar Mar 26 '25 19:03 azrogers

Our native code holds references to managed objects, which will keep them from being garbage collected. So, under normal circumstances, a managed object can't completely go away on us. However, there are two possible exceptions to this:

  1. While the managed object reference will still be valid, the value of it may become invalid. For example, Unity may destroy its own native object underlying a managed one. Comparing Unity objects against null actually checks this case via some dodgy operator overloading within Unity.
  2. When the AppDomain unloads - which Unity is rather fond of doing - our managed references will be invalidated. In thoery we can subscribe to notification of AppDomain unload and handle it "somehow". More details about this here: https://github.com/CesiumGS/cesium-unity/pull/536

kring avatar Mar 27 '25 22:03 kring