Unity Editor crashes when initializing world with Monitor and Metrics modules
seep opened this issue · 2 comments
Minimal repro is to add this MonoBehaviour to an empty scene:
using Flecs.NET.Core;
using UnityEngine;
public class FLECSBootstrap : MonoBehaviour
{
private World world;
private void Start()
{
world = World.Create();
world.Import<Ecs.Monitor>();
world.Import<Ecs.Metrics>();
}
private void Update()
{
world.Progress();
}
}
Strangely, it only crashes on the second time running the scene. Windows 11 x64 and debug native libs.
This bug is a known issue in multi-world applications. The details of the issue are discussed here SanderMertens/flecs#1032. The link talks about the C++ API, but most of it applies to the C API too.
The flecs C API stores component ids in global variables which are usually only valid in the first world they are created in. From what I understand, Unity does not unload dlls between consecutive plays, so when you run the scene for the second time, the component ids from the first world are still retained in their respective global variables. If components/entities are not registered in the exact same order as they were in the first world, a number of different assertions can fail.
The crash you're running into can be reproduced in C++ with the following code. An assertion happens because one of the module components points to an id that hasn't been registered in the second world yet.
#include "flecs.h"
int main(int argc, char *argv[]) {
flecs::world a;
a.import<flecs::monitor>();
a.import<flecs::units>();
flecs::world b;
b.import<flecs::monitor>();
b.import<flecs::units>();
}
The actual problem happens from inside of flecs so it's not something I can directly fix at a wrapper level. One solution that I'm looking into right now is to manually handle the loading/unloading of dlls in the bindings but I'm not sure if that's possible yet.
This is fixed, presumably by SanderMertens/flecs@2f8ad57 (at least, that was when the corresponding test case was added).