Search Unity

change color of ui in update

Discussion in 'Editor & General Support' started by ghiboz, Sep 27, 2018.

  1. ghiboz

    ghiboz

    Joined:
    Sep 7, 2012
    Posts:
    465
    hi all!

    I need to change a text color in the update function...
    what's the better way to do this?
    (impacting less time?)

    this?
    Code (CSharp):
    1. if (ChronoSec < ChronoStop)
    2. {
    3.     if (UiTimer.color != Color.red)
    4.     {
    5.         UiTimer.color = Color.red;
    6.     }
    7. }
    or this?
    Code (CSharp):
    1. if (ChronoSec < ChronoStop)
    2. {
    3.     UiTimer.color = Color.red;
    4. }
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    The second one is more optimized because calling UiTimer.color calls a "property getter" function in the background, and calling "Color.red" is like calling "new Color(1, 0, 0, 1)".

    Your first snippet calls a property getter once, property setter once, and "new Color" twice.
    By comparison, your second snippet only calls a property setter once, and "new Color" once.


    That said, this is a very minor optimization. I would not worry about such little things unless your game is running slow or you are working on a huge AAA game that needs every little performance boosts it can get to achieve top-tier graphic effects.
     
  3. ghiboz

    ghiboz

    Joined:
    Sep 7, 2012
    Posts:
    465
    thank you @Gambit-MSplitz

    the first snippet comes from a old thing on winforms, where if I set the color each time, it blink...