Search Unity

Question How to avoid outer closure garbage?

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

  1. Luemus

    Luemus

    Joined:
    May 20, 2013
    Posts:
    107
    Hi everyone! I am trying to avoid creating garbage. I've seen this post about avoiding garbage with outer closures. I've tried the delegate solution however I got an error that says;

    error DC0044: Entities.ForEach can only be used with an inline lambda. Calling it with a delegate stored in a variable, field, or returned from a method is not supported.

    So, I guess this is not supported anymore. Is there an alternative way? Thanks all!

    For the context, here is the code;
    Code (CSharp):
    1. var thrust = _playerControls.Ship.Thrust.ReadValue<float>();
    2.  
    3. Entities
    4.     .WithAll<PlayerSpaceship, SpaceshipMotorInput>()
    5.     .ForEach((ref SpaceshipMotorInput input) =>
    6.     {
    7.         // outer closure of 'thrust' variable
    8.         input.Thrust = thrust;
    9.     }).Schedule();
     
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    Entities.ForEach does not produce garbage on its own despite contrary beliefs.
    Since code you write is actually replaced by the codegen (by using source generators).
    Check generated code for the system for more details.

    If you're using Rider, you can turn off analysis for it with a comment in a file such as:
    Code (CSharp):
    1.    // Replaced by codegen
    2.    // ReSharper disable HeapView.ClosureAllocation
    3.    // ReSharper disable HeapView.DelegateAllocation
    I'm using it as a part of template. Rider is good, but does not include proper analysis for EFE.
    Though be careful if used with managed systems and doing tricky stuff, as those will disable analysis delegate / capture analysis for the whole file.


    What is not supported though is managed objects with .Schedule. Counting delegates & anonymous classes.

    If you want to read value from separate Entity inside job - use either ComponentDataFromEntity or ComponentLookup depending on what version of Entities you're using.
     
    Last edited: Oct 13, 2022
    vectorized-runner, Singtaa and Luemus like this.