Search Unity

Question Spawning a list of prefabs with a system

Discussion in 'Entity Component System' started by seona13, Dec 7, 2022.

  1. seona13

    seona13

    Joined:
    Nov 28, 2019
    Posts:
    24
    Not sure how much sense that subject makes, but I'm having trouble wording it.

    I have a set of prefabs - motes of light in different colours, each with a different behaviour. I want to spawn in a certain number of each one, as entities so that I can take advantage of all of the ECS speed and efficiency goodness.

    I have two options for doing this that I can see:
    1/ Have my array of prefabs in the Spawner component
    2/ Have my array of prefabs in my Config (which is a garden-variety MonoBehavior)

    Making arrays in components seems to be horrendously complicated, and I've yet to find an article on it that makes enough sense to me that I feel I could turn around and use it.

    Pulling in GameObjects from a MonoBehavior script runs up against the problem of needing to convert them to entities. The only stuff I've been able to find online about doing this uses the now-deprecated method of attaching the ConvertToEntity script to the prefab.

    Can anybody help me either figure out how to put an array into a component (in a way that I can expose it to the Unity editor in my Authoring script so I can drag-and-drop the prefabs into it) or alternatively how to convert the GameObject prefabs into Entities?
     
  2. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    4,271
    Code (CSharp):
    1. public struct Spawnable : IBufferElementData
    2. {
    3.     public Entity prefab;
    4. }
    5.  
    6. public class SpawnerAuthoring : MonoBehaviour
    7. {
    8.     public GameObject[] prefabs;
    9. }
    10.  
    11. public class SpawnerBaker : Baker<SpawnerAuthoring>
    12. {
    13.     public override void Bake(SpawnerAuthoring authoring)
    14.     {
    15.         if (authoring.prefabs == null || authoring.prefabs.Length == 0)
    16.             return;
    17.  
    18.         var buffer = AddBuffer<Spawnable>().Reinterpret<Entity>();
    19.         foreach (var prefab in authoring.prefabs)
    20.             buffer.Add(GetEntity(prefab));
    21.     }
    22. }