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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

TextMesh alpha

Discussion in 'Scripting' started by FanOfLearning, May 5, 2022.

  1. FanOfLearning

    FanOfLearning

    Joined:
    Oct 22, 2021
    Posts:
    5
    Hello.

    Code (CSharp):
    1.     private TextMesh textMesh = null;
    2.  
    3.     private void Awake()
    4.     {
    5.         textMesh = GetComponent<TextMesh>();
    6.     }
    7.  
    8.     private void Update()
    9.     {
    10.         Debug.Log(textMesh.color.a);
    11.         float a = textMesh.color.a;
    12.         Debug.Log(a);
    13.         a -= Time.deltaTime * 0.1f;
    14.         Debug.Log(a);
    15.         textMesh.color = new Color(1, 1, 1, a);
    16.         Debug.Log(textMesh.color.a);
    17.     }
    Output:
    1
    1
    0.998
    0.996

    I don't understand, what's wrong with this code?
     
  2. karliss_coldwild

    karliss_coldwild

    Joined:
    Oct 1, 2020
    Posts:
    530
    Color isn't necessarily stored as 4x4 byte floats. That would be 32 bits per component. Often its stored as 8 bits per component (32bit total) or sometimes 10bits per component if you are generous. 0.996 is very close to 254/255 so most likely at some point color is stored as 4 bytes.
     
    FanOfLearning likes this.
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,748
    You could have been a lot more specific about the problem you were seeing - it took me a minute to figure out what I think you're expecting.

    Most likely either the Color struct or the textMesh.color property is converting the float value of 0.998 into a 0-255 integer value, because when you're actually outputting colors, that's all the precision you need. So when you set it to .998, it internally sets the value to 254, which is as close to accurate that 0-255 can get with that input.

    254 / 255 = 0.9960784314. So when you go to get the value back out, that's the value you receive.

    If that is a problem, then store the alpha value in your own class and don't read back the .color value.
     
    FanOfLearning likes this.
  4. FanOfLearning

    FanOfLearning

    Joined:
    Oct 22, 2021
    Posts:
    5
    My text was fading very slowly and color.a was stuck at 0.956 at some point. It makes sense now.
    Thank you very much for the explanation and sorry for not describing the problem clearly.
     
  5. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,150
    Just a recommendation. I'd look into a tweening library such as leantween or dotween. Both are free on the asset store and can help with stuff such as fades a little easier.