Search Unity

Should I avoid updating transform/GameObject variables if they haven't changed?

Discussion in 'Getting Started' started by mortoray, Dec 17, 2022.

  1. mortoray

    mortoray

    Joined:
    Sep 14, 2018
    Posts:
    94
    I have objects that respond to changes in global state (typical state-based design) during the call to `Update`. I'm wondering whether it is efficient to always update the values, or whether I need to cache the values and only update those that have changed.

    For example, in pseudo-code, can I simply do:

    Code (CSharp):
    1.  
    2. var newPos = getStatePos();
    3. var newRot = getStateRot();
    4. transform.SetPositionAndRotation(newPos, newRot);
    5.  
    Or should I be doing something like:

    Code (CSharp):
    1.  
    2. var newPos = getStatePos();
    3. var newRot = getStateRot();
    4. if ( newPos != curPos || newRot != curRot ) {
    5.     transform.SetPositionAndRotation(newPos, newRot);
    6.     curPos = newPos;
    7.     curRot = newRot;
    8. }
    9.  
    The same question applies to things like material.color, or basically anything else that can be changed. Does it cost anything to set the same value again and again?