Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Instantiate entities from code

Discussion in 'Entity Component System' started by Attatekjir, Apr 13, 2020.

  1. Attatekjir

    Attatekjir

    Joined:
    Sep 17, 2018
    Posts:
    23
    I wish to instantiate entities from a JobComponentSystem in the OnUpdate upon pressing spacebar. To be able to spawn the desired entities i need their prefab. JobComponentSystems lack the functionality of serialisable fields to which one can drag a prefab in. How do i load a prefab into a JobComponentSystem in order to spawn them?

    The example scene from ECSSamples > HelloCube > 6. SpawnAndRemove that is supposed to show spawning entities from code is not complete (no entities re-spawn).
     
  2. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    3,993
    So SpawnerSystem_SpawnAndRemove.cs only needs two modifications to get what you want. First, you need to delete the commandBuffer.DestroyEntity line. And second, you need to wrap the Entities.ForEach inside an if (spacePressed).
     
  3. Attatekjir

    Attatekjir

    Joined:
    Sep 17, 2018
    Posts:
    23
    Great, thank you for the swift reply. This enables me to assign the field "private Entity prefab" in my JobComponentSystem with the prefab reference found on a holding entity. To this holding entity I can assign prefabs to in the editor.

    I wish we could somehow directly load the prefab into a JobComponentSystem.
     
  4. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    3,993
    While I could provide several reasons why not, I am very curious. Why?
     
  5. brunocoimbra

    brunocoimbra

    Joined:
    Sep 2, 2015
    Posts:
    677
    It may be an option in the future when we have proper Addressables support in ECS
     
  6. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    3,993
    Serializing Addressables directly to systems kinda defeats the point of Addressables. Most likely there will be some API exposed by either World or some Unity system added to World that has methods for loading Addressables.
     
  7. Attatekjir

    Attatekjir

    Joined:
    Sep 17, 2018
    Posts:
    23
    Loading a prefab into the JobComponentSystem directly would be one step less than loading the prefab onto an entity and then reading it to the JobComponentSystem ;).
     
  8. brunocoimbra

    brunocoimbra

    Joined:
    Sep 2, 2015
    Posts:
    677
    Yeah, this is what I would expect, so this would allow us to access prefabs without requiring to first convert a prefab and storing the entity prefab somewhere else (like a singleton) just for spawning stuff.