Search Unity

const / static in ComponentData

Discussion in 'Entity Component System' started by aeldron, Mar 18, 2019.

  1. aeldron

    aeldron

    Joined:
    Feb 12, 2013
    Posts:
    32
    Hello.

    What is the best practice to declare your const values?

    Sometimes we may have some data we know will be identical for all of our entities. For instance:

    Code (CSharp):
    1. public struct ScaleComponent: IComponentData
    2. {
    3.     public const float MinScale = 0.05f;
    4.     public static float MaxScale = 20.0f;
    5.     public float CurrentScale;
    6. }
    Is it preferable to place those in a ComponentData, or should they be properties on a System class?

    Code (CSharp):
    1. public class ScaleSystem: ComponentSystem
    2. {
    3.     protected const float minScale = 0.05f
    4.     protected const float maxScale = 20.0f;
    5.  
    6.     protected override OnUpdate() {}
    7. }
    I'm not keen about putting that data on my system class. This breaks the separation between data and behaviour which the ECS revolves around. Also, if that data was needed on another system we would need to declare it again.

    On the other hand, am I right to think that putting a const or static property on my ComponentData, it might not be in the same chunk we're loading to the cache?
     
  2. JPrzemieniecki

    JPrzemieniecki

    Joined:
    Feb 7, 2013
    Posts:
    33
    Neither const nor static ever go into chunks.
    Const values are inlined wherever they are used, and static variables live somewhere in the managed memory (one memory location per variable, not per object instance).
     
    aeldron likes this.
  3. Leuthil

    Leuthil

    Joined:
    Jul 26, 2013
    Posts:
    97
    Isn't this what SharedComponentData is for?

    For example:
    ScaleLimit shared component which has min and max.
    Scale component which has current scale.
     
    Last edited: Mar 24, 2019
    aeldron likes this.
  4. aeldron

    aeldron

    Joined:
    Feb 12, 2013
    Posts:
    32
    I think you're right. That's also a more flexible solution, imagine a group of entities has a different scale range, SharedComponentData is ideal for that.
     
  5. JPrzemieniecki

    JPrzemieniecki

    Joined:
    Feb 7, 2013
    Posts:
    33
    My (rough) rules of thumb:
    Is the value the same for all places it is used, and never changes? -> use const
    Is the value the same for all places it is used, but can change at runtime or has to be loaded from a file, computed at init time etc? -> use static or (preferably) singleton components.
    Is the value different per (reasonably large) group of entities, or you want to use the filter-by-sharedcomponent functionality? -> use shared components
    Is the value different per entities, or the groups sharing the value are small? -> use normal components