hoangtongvu / ECS-DEMO

Demo Unity Project using ECS.
2 stars 1 forks source link

New UISpawner class SOMETIME cause Exception " object of type 'x' has been destroyed but you are still trying to access it." #13

Open hoangtongvu opened 7 months ago

hoangtongvu commented 7 months ago

New UISpawner class: https://github.com/hoangtongvu/ECS-DEMO/blob/66fe15c402ee6e15a522d75b132bf9644439a3bf/Assets/_Scripts/Core/Spawner/UISpawner.cs I belive UISpawner uses valid data cause Spawn() only used in OnUpdate().

The said x is:

BaseUIPool above exists in the scene and get registered by UIPoolMapRegister https://github.com/hoangtongvu/ECS-DEMO/blob/66fe15c402ee6e15a522d75b132bf9644439a3bf/Assets/_Scripts/Core/UIPoolMapRegister.cs and in gameplay hierachy, BaseUIPool is not destroyed.

hoangtongvu commented 7 months ago

Fixed: By adding Transform field into UIPoolMapValue and use it directly instead of accessing it through transform of uiPool. This may be a bug of the way ECS Package stores monobehaviour in ICD (managed type), we are only able to access property/method that we declared ourselves in the said x, accessing any property/method in monobehaviour (even though x is monobehavior) will lead to said Exception.

hoangtongvu commented 7 months ago

Found the root problem. It comes from UISpawner (which is singleton one, used lazy initialization, and is not monobehaviour), singleton instance of UISpawner won't cleaned up by Unity automatically, which mean when enter playmode at time n, we still use singleton instance of the first time playmode (use old data of ICD, that why Unity said that 'x' has been destroyed but I am still trying to access it). The above solution I provided is not really fix it. Instead, call public static void DestroyInstance() => instance = null; of UISpawner in OnDestroy() in any Monobehaviour manually to free the singleton instance.

hoangtongvu commented 7 months ago

Another solution: Use [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]: https://github.com/laicasaane/unity-addressables-manager/blob/6e405a103fa5f19f2f94c311ea84efcacb3ebadc/AddressablesManager/AddressablesManager.cs?fbclid=IwZXh0bgNhZW0CMTAAAR1WlbVE6Opr586fRwhVOysJb35tmK6vHaI03l_xyiePnFwLXk9wp0xcnH4_aem_AePo3NwUOEzLfjqNGwwF91V3dtDUMFZn4EerVXQZ_LESY29cgoFZwUkb-BaNi3RLGIitSdfk1xUt-locbKiJLOQP#L49