Add entity to GameObject

Is it possible to add an existing entity to a GameObject (or vise versa)? I know the ConvertToEntity workflow allows you to create a new entity and associate it with a GameObject (and it’s representative MonoBehaviour components). But I am looking for ways to associate existing entities and GameObjects with one another.

You can make an Entity field in a MonoBehaviour component which sits on a gameobject, but I don’t think there is a way to go in reverse, from an ECS component back to a reference in the gameobject world without doing it manually like making a dictionary where the entity is the key that points to a GameObject value.

Or if specifically you’re talking about during Conversion, how to get an already-existing entity that was created for some other object, try GetPrimaryEntity()

You probably need some sort of custom tween / tweening mechanism. If you search these terms you will find some suggestions.

I personal used Native Array in past, to store pairs of GO-Entities. Hash map could work too in certain conditions.

Figured it out after some digging:

GameObjectEntity.AddToEntity(EntityManager, gameObject, entity);
2 Likes

Looks like some potentially nice features.

Found a bug when destroying a GameObject with the following method:

GameObjectEntity.Destroy(gameObject);

Though it destroys the GameObject and all it’s MonoBehaviour components, the MonoBehaviour components are still queryable (though their values in the array are null). As a work around, I found that I had to manually remove these components before destroying the GameObject, like so:

var components = gameObject.GetComponents<Component>();

for (var i = 0; i < components.Length; i++)
{
    EntityManager.RemoveComponent(entity, components[i].GetType());
}
1 Like

I highly recommend avoiding using anything GameObjectEntity related. Just going to come back and bite you at some point.

1 Like

How come? What issues have you experienced with using it?

Main issue is - it will be removed in one of future releases.

1 Like

Do you know of alternatives to this approach? Or do you know if Unity will provide other ways of doing this when they depreciate GameObjectEntity in future releases?

Just experimented with directly adding the MonoBehaviour components to the entity without GameObjectEntity, and this works great and is exactly what I am looking for:

var components = gameObject.GetComponents<Component>();

for (var i = 0; i < components.Length; i++)
{
    EntityManager.AddComponentObject(entity, components[i]);
}

So yeah, no need for GameObjectEntity, it’s pretty strait forward and easy to do it yourself manually.

1 Like