Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

Instantiate Random entity from EntityGroup?

Discussion in 'Project Tiny' started by Grillbrick, Mar 19, 2019.

  1. Grillbrick

    Grillbrick

    Joined:
    Jul 17, 2015
    Posts:
    9
    Is there a way to instantiate a random entity from an entity group instead of spawning the entire group? I know there are prefabs now, but it is much simpler in my case to have a single prefab and simply change the sprite than to create multiple prefabs.
     
  2. raymondyunity

    raymondyunity

    Unity Technologies

    Joined:
    Apr 30, 2018
    Posts:
    122
    Is it possible to just make that entity an EntityGroup? It is fine to have only one entity in an EntityGroup.
     
  3. sniffle63

    sniffle63

    Joined:
    Aug 31, 2013
    Posts:
    365
    I could of misunderstood what your asking but if you want to spawn a single entity from an entity group you can do this,

    Code (JavaScript):
    1. ut.EntityGroup.instantiate(world, entityGroup)[entityIndex]
    a full function for doing it with a transform position could look like this


    Code (JavaScript):
    1.     export function Spawn(world: ut.World, entityGroup: string, position: Vector3 = null, entityIndex: number = 0) {
    2.  
    3.         let ent = ut.EntityGroup.instantiate(world, entityGroup)[entityIndex];
    4.  
    5.         if (position != null) {
    6.             world.usingComponentData(ent, [ut.Core2D.TransformLocalPosition], (transformLocalPosition) => {
    7.  
    8.                 transformLocalPosition.position = position;
    9.             });
    10.         }
    11.         return ent;
    12.     }
     
  4. Rupture13

    Rupture13

    Joined:
    Apr 12, 2016
    Posts:
    131
    This actually does not just spawn a single entity from an entityGroup, but rather spawns the entire entityGroup and returns just the entity at the given index. If you don't add the
    [entityIndex]
    , the function returns a full list with all spawned entities of the entityGroup.


    It's probably best to do as raymond suggested: to make entity""Groups"" with one entity (which would be the random entity you want to spawn) and then choose the random entity by first selecting a random string (entityGroup name) and instantiating the entityGroup from that random string.
    You could for example make a component that has an array field of strings representing your random entities by entityGroup name. Your code could then pick a random value from this component to spawn your entity.