Hi all,
I’m pondering some Entity + GameObject integration for things where the ECS approach is a little lacking, or where there are already some very developed GameObject/MonoBehavior systems but ECS would be beneficial for another system. But also I’m mostly just thinking about this to play around with things.
Associating an Entity with a GameObject is very straightforward. You just need a field. Associating a GameObject with an Entity is a little more involved. I see two easy ways.
1) Create a component class that inherits from IComponentData that contains a field for a GameObject. I haven’t seen this fully documented, but I found it in the threads here (thanks peeps). The ChangeLog suggests what we might suspect. Using an IComponentData class “allows managed types such as GameObjects or List<>s to be stored in components. Users should use managed components sparingly in production code when possible as these components cannot be used by the Job System or archetype chunk storage and thus will be significantly slower to work with. Refer to the documentation for component data for more details on managed component use, implications and prevention.”
2) Use EntityManager.AddComponentObject to add a GameObject to an Entity. The GameObject can be removed with RemoveComponent. As far as I can tell, there is not a command buffer equivalent (you can add the GameObject, but I’m not sure how to set it). The documentation notes that “Accessing data in a managed object forfeits many opportunities for increased performance. Adding managed objects to an entity should be avoided or used sparingly.”
3) A third option I have seen on these forums and elsewhere is to keep a central storage of GameObjects, and simple give an Entity a Component with an index to its associated GameObject, or to use use the Entity as a key to retrieve the GameObject.
From what I can tell, these first two methods seem to be equivalent. I believe the Entity with the components still function as normal in a Chunk, but anything done with the GameObjects themselves will naturally be slower. Of these two preference here would be 1) the component class, simply because it seems to be more flexible.
I think that method 3) would also perform similarly. The ECS parts of the code should be efficient, and then anything that needs the GameObject with have limitations. Depending on use, I could see this method having some benefits in reducing Entity Archetype changes. For example, if GameObjects are stored in an array, a IComponentData int with a value of -1 could indicate no associated GameObject, while any other value would indicate the position in the array. Similarly, If Entities were used as keys for GameObjects, it would be easy to associate, or not associate, an Entity with a game object without any Archetype change. I could see this approach being nice in some cases.
I’m curious what general thoughts you all might have.