Search Unity

How to best handle entity references that should be duplicated upon instantiation?

Discussion in 'Entity Component System' started by PhilSA, Oct 7, 2019.

  1. PhilSA

    PhilSA

    Joined:
    Jul 11, 2013
    Posts:
    1,926
    Ok so I have this use case:
    • I have a "Gun" component
    • The Gun has an Entity field that represents the "BulletPrefabEntity"
    • The Gun also has an Entity field that represents the "BulletSpawnPointEntity"
    I begin by doing the following in order to convert my Gun to entities for fast instantiation:
    Code (CSharp):
    1. Entity startingGunPrefabEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(PlayerStartingGunPrefab, World.Active);
    And afterwards, in game, I Instantiate the Gun like so:
    Code (CSharp):
    1. Entity gunEntityInstance = entityManager.Instantiate(startingGunPrefabEntity);
    Now I have a problem.
    Both the "BulletPrefabEntity" and the "BulletSpawnPointEntity" refer to the original converted entities. This is what I want for the "BulletPrefabEntity", but it's not what I want for "BulletSpawnPointEntity". The bullet spawn point should be duplicated in order to represent the one attached to the gun I instantiated.

    I understand how it makes perfect sense that "Instantiate" does not automatically duplicate entities like I just described, but I was wondering how you guys handle cases like these. Would you make a custom instantiation function for the gun? Is there some kind of [DuplicateEntityReference] attribute I can put over Entity fields that should be duplicated? Etc, etc.....

    Instantiating from the GameObject prefab and letting the conversion do its thing would be a solution to this problem, but it is waaaaaay more expensive than instantiating from the already-converted entity so I'd prefer to avoid it
     
    Last edited: Oct 7, 2019