Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question how to set only some values of a component?

Discussion in 'Entity Component System' started by tzxbbo, Aug 18, 2023.

  1. tzxbbo

    tzxbbo

    Joined:
    Dec 14, 2019
    Posts:
    57
    Let's say I'm trying to spawn a bunch of enemies,

    I created an entity command buffer and use it to instantiate my enemy.
    Entity enemy = ecb.Instantiate(enemyPrefab);


    then I need to set the enemy's spawn position so I'll need to call setcomponent()
    ecb.SetComponent(enemy, new LocalTransform(){...})


    The problem is the way we set component is basically creating a new component and replace it with the old one ( it seems, I'm not certain)

    In this case, I only care about setting position data, but not the whole LocalTransform, for example the scale is set in the inspector and I don't want to touch it.

    Or maybe I'm totally wrong? setcomponent() will compare and only set data that's different? so there's no need to worry at all
     
  2. Laicasaane

    Laicasaane

    Joined:
    Apr 15, 2015
    Posts:
    288
    Correct. SetComponent = replace entirely.
     
    xVergilx likes this.
  3. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,292
    - Store initial transform or values (e.g. during baking);
    - Use a copy of initial data during initialization;
    - Modify position
    - Apply the whole struct.

    Alternatively, you could also read data directly from the prefab entity.
    But that should be slower in theory depending on the numbers.
     
  4. tzxbbo

    tzxbbo

    Joined:
    Dec 14, 2019
    Posts:
    57
    Thanks, looks like we shouldn't have too much data packed in one component, otherwise it would a pain to call setcomopnent
     
  5. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,292
    Ideally, it shouldn't matter, since structural changes should be used rarely.
    But when it happens, well its a bit more typing. Its not that bad though.

    Since all components are structs, you'd just copy the whole thing in one go, then apply diff.
    It takes less code than to describe what is required to be done. E.g.
    Code (CSharp):
    1. T someData = initialData;
    2. someData.Position = value;
    3.  
    4. ecb.SetComponent(entity, someData);
    As for the prefab related data. You'd want some kind of "settings" that have a prefab inside it.
    So storing required extra values / settings shouldn't be a big deal.
     
  6. poon2

    poon2

    Joined:
    Oct 30, 2022
    Posts:
    10
    1. In your spawn system, read LocalTransform from the prefab and store in local variable.
    2. Change Position on that LocalTransform local variable
    3. Call SetComponent on ECB with that LocalTransform.