Search Unity

Get entity count of a ForEach before going through the ForEach

Discussion in 'Entity Component System' started by Guedez, May 8, 2019.

  1. Guedez

    Guedez

    Joined:
    Jun 1, 2012
    Posts:
    827
    So this is my old deprecated code:

    Code (CSharp):
    1.     public unsafe struct CropTileQuerry {
    2.         public CropTile* tile;
    3.         public Transform transform;
    4.     }
    5.     public unsafe void Serialize(BinaryWriter bw) {
    6.         ComponentGroupArray<CropTileQuerry> componentGroupArray = GetEntities<CropTileQuerry>();
    7.         bw.Write(componentGroupArray.Length);
    8.         foreach (CropTileQuerry q in componentGroupArray) {
    9.             Vector3 position = q.transform.position;
    10.             bw.Write(position.x);
    11.             bw.Write(position.y);
    12.             bw.Write(position.z);
    13.         }
    14.     }
    I would save the length before saving the positions, but I can't really do that with ForEach as far as I am aware. Right now I am setting the BinaryWriter
    BaseStream
    Position
    back after counting and writing the positions to write at the beginning the total amount of crop tiles, but I am not sure that even works. Is there any ECS way to count the total amount of entities before iterating them?
     
  2. TLRMatthew

    TLRMatthew

    Joined:
    Apr 10, 2019
    Posts:
    65
    Using an EntityQuery you can. Assuming this code is running inside a ComponentSystemBase:

    Code (CSharp):
    1. EntityQuery query = GetEntityQuery(
    2.             ComponentType.ReadOnly<CropTileQuerry>()
    3. );
    4.  
    5. int count = query.CalculateLength();
    Then you can get out a NativeArray of the Entities:

    Code (CSharp):
    1. var entities = query.ToEntityArray(Allocator.Temp);
    2. ...
    3.  
    4. entities.Dispose();
     
    apelsinex, DotusX and Guedez like this.
  3. Guedez

    Guedez

    Joined:
    Jun 1, 2012
    Posts:
    827
    Nice, also, ToEntityArray is faster than ForEach?
     
  4. TLRMatthew

    TLRMatthew

    Joined:
    Apr 10, 2019
    Posts:
    65
    I'm not aware of a way to foreach on an EntityQuery unless you're using it to Schedule an IJobForEach, but I haven't used non-job ComponentSystems much so I could be missing something!
     
  5. elcionap

    elcionap

    Joined:
    Jan 11, 2016
    Posts:
    138
    Code (CSharp):
    1. void OnUpdate() {
    2.     var count = myEntityQuery.CalculateLength();
    3.     Entities
    4.         .With(myEntityQuery)
    5.         .ForEach((...) => {
    6.             ...
    7.         });
    8. }
    []'s
     
    DotusX and TLRMatthew like this.