Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to Instantiate Game Objects in ComponentSystem?

Discussion in 'Entity Component System' started by DedRed, Mar 12, 2019.

  1. DedRed

    DedRed

    Joined:
    Jan 16, 2013
    Posts:
    4
    Have a reference to a prefab with a GameObjectEntity component on it. When I instantiate the plain ol' Object.Instantiate way it will only spawn one object. If there's one of those objects in the scene already it won't instantiate a new one. Seems like it adds an entity shown in the Entity Debugger correctly.

    If I use the approach used in the SpaceShooter example project with EntityManager.Instantiate, passing in my prefab, it spawns the right amount of entities at the right time in the Entity Debugger, but those entities don't have any components on them and of course it shows nothing in the scene.

    In a hybrid ECS scenario I haven't been able to find an example that can spawn a game object from a ComponentSystem that works for me.
     
  2. kstothert

    kstothert

    Joined:
    Dec 8, 2016
    Posts:
    68
    Code (CSharp):
    1. var prefab = somePrefabWithGameObjectEntityAttached;
    2.  
    3. GameObject.Instantiate(prefab);
    that will work to spawn as many as you need from a system, however it will invalidate native arrays since it creates the entity immediately.

    if you are using preview 26/27 you can have it automatically create the entity for all your prefabs using
    IConvertGameObjectToEntity
    and
    IDeclareReferencedPrefabs
    these will allow you to store prefabs in the inspector as a gameobject but they will be converted to entites (you have to add the ConvertToEntity component on any prefabs). Then your gameobject prefab will be stored as a preconverted entity by the time your system get it so you can simply use
    EntityManager.Instantiate(convertedEntityPrefab)
    . This workflow is recommended and should soon replace
    GameObjectEntity
    entirely.

    Example code https://github.com/Unity-Technologi...oCube_06_SpawnFromEntity/HelloSpawnerProxy.cs
     
    nicolasgramlich likes this.
  3. coldasfrost979

    coldasfrost979

    Joined:
    Jun 9, 2018
    Posts:
    25

    Hello,

    Thank you for helping out with this. I am trying to wrap my head around how to use the IConvertGameObjectToEntity. I have a prefab that I have added the ConvertToEntity script to. However, I tried to follow the link you provided to take it home so to speak. Unfortunately the link returns a 404. Do you know of any other examples?
     
  4. kstothert

    kstothert

    Joined:
    Dec 8, 2016
    Posts:
    68
  5. coldasfrost979

    coldasfrost979

    Joined:
    Jun 9, 2018
    Posts:
    25
    Thank you!
     
  6. TheXWolf

    TheXWolf

    Joined:
    Dec 13, 2013
    Posts:
    85