Search Unity

Question What is wrong here?

Discussion in 'Entity Component System' started by Luemus, Oct 12, 2022.

  1. Luemus

    Luemus

    Joined:
    May 20, 2013
    Posts:
    107
    Hi, I've been looking on entity queries however for some reason I can't change the velocity of the player. First I created an entity query, something like this;

    Code (CSharp):
    1.             _entityQuery = new EntityQueryBuilder(Allocator.Temp)
    2.                 .WithAll<PlayerInput, PlayerMovement>()
    3.                 .WithAllRW<PhysicsVelocity>()
    4.                 .Build(this);
    And then, inside the update method I did something like this;

    Code (CSharp):
    1.             var inputs = _entityQuery.ToComponentDataArray<PlayerInput>(Allocator.Temp);
    2.             var movements = _entityQuery.ToComponentDataArray<PlayerMovement>(Allocator.Temp);
    3.             var velocities = _entityQuery.ToComponentDataArray<PhysicsVelocity>(Allocator.Temp);
    4.          
    5.             for (var i = 0; i < inputs.Length; i++)
    6.             {
    7.                 var input = inputs[i];
    8.                 var movement = movements[i];
    9.                 var velocity = velocities[i];
    10.              
    11.                 velocity.Linear = new float3
    12.                 {
    13.                     x = input.MovementInput.x * movement.Speed,
    14.                     y = input.MovementInput.y * movement.Speed,
    15.                     z = 0
    16.                 };
    17.              
    18.                 velocities[i] = velocity;
    The problem is that the velocity is not being applied. I've added the system to the
    FixedStepSimulationSystemGroup
    and marked it to update before the
    PhysicsSystemGroup
    .

    After failing I decided to try it in another way, and this is how I got it done;
    Code (CSharp):
    1.             Entities.ForEach((
    2.                 ref PhysicsVelocity velocity,
    3.                 in PlayerInput input,
    4.                 in PlayerMovement movement) =>
    5.             {
    6.                 velocity.Linear = new float3
    7.                 {
    8.                     x = input.MovementInput.x * movement.Speed,
    9.                     y = input.MovementInput.y * movement.Speed,
    10.                     z = 0
    11.                 };
    12.             }).Schedule();
    However, I am still curious about the first one. What was the reason that I wasn't able to write to the PhysicsVelocity?
     
  2. Anthiese

    Anthiese

    Joined:
    Oct 13, 2013
    Posts:
    73
    The first version you provided uses new buffers that are merely copies of the original chunk data. Writes to those arrays are only writes to a copy of the data, not the original. The second way is pretty much the default way you should have gotten it done.
     
    Last edited: Oct 12, 2022
    Luemus likes this.