Entities.WithAll<>().ForEach analog for MonoBehaviour

Is it possible to change entity data from MonoBehaviour? In my case, I want to change entity data onTriggerEnter event.

Yup. Just use “World.Active.EntityManager”. Or if you have the latest version downloaded, it has been changed to “World.DefaultGameObjectInjectionWorld.EntityManager”

You can call a method on a system to do it.

Any example please?

If your Monobehaviour has a reference to the entity you want to update then just doing the following will update it:

World.DefaultGameObjectInjectWorld.EntityManager
     .SetComponentData(entity, new MyData { blah = 2 });

But if you want to query an array of data and update that, then you can call the update function on a system that does the querying and updating you want. You can do this like so inside your OnTriggerEnter function:

World.GetOrCreateSystem<MySystem>().Update();

You’ll probably want to put the “[DisableAutoCreation]” attribute on top of that system so it doesn’t get created and updated by the EntityManager since it would be a system that you’d want to update manually in your OnTriggerEnter function.

Thanks. And how to transfer data from Monobehaviour to ComponentSystem?

That depends. What exact data are you trying to transfer? And what exact problem are you trying to solve?

I am trying to solve a problem in order to change the value of IComponentData in Monobehaviour. In my case, when various objects enter an area, they must transmit values depending on which object it is. You said that I can create a system that will update this value. I can create 10 such different systems for 10 different objects. Or I can simply pass 10 values for the same system.

I had to solve a similar problem to that recently. For this I would recommend the entity event pattern instead of having your MonoBehavior directly update a system. Basically, inside your OnTriggerEvent function, use “World.DefaultGameObjectInjectWorld.EntityManager” to create a new entity. On this new entity put all the information about the object that entered the area. Then create a system that processes this data. And then also create a CleanUp system that deletes this entity event you created. So the order of operation would look something like this:

- Monobehavior.OnTriggerEnter
     - EntityManager.CreateEntity(typeof(EntityEvent), typeof(InfoAboutObject));
- ProcessInfoAboutObjectSystem [UpdateBefore(typeof(DeleteEntityEventSystem))]
     - ForEach((ref EntityEvent entityEvent, ref InfoAboutObject data) => //do stuff);
- DeleteEntityEventSystem ->
     - ForEach((Entity entity, ref EntityEvent entityEvent) => PostUpdateCommands.DestroyEntity(entity);
2 Likes

Thanks, it works.