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

Resolved How to Change the Alpha of a Material In Code

Discussion in 'Scripting' started by CodeUnit07, Aug 20, 2023.

  1. CodeUnit07

    CodeUnit07

    Joined:
    Aug 10, 2023
    Posts:
    11
    Sup everyone,

    I have a loading screen in my game which I want to fade out when I tell it to. I started by making an object for which I attached a material. I changed the rendering mode to fade and by changing the alpha in the Albedo section I can get a variable alpha manually.

    My question comes to changing it in the code. I've been doing the following:

    Code (CSharp):
    1. public Material myMaterial;
    2. public float alphaChange = 255;
    3.  
    4. void Update()
    5. {
    6.     alphaChange -= 50;
    7.  
    8.     if (alphaChange < 0)
    9.     {
    10.         alphaChange = 0
    11.     }
    12.  
    13.     myMaterial.color = new Color(0, 0, 0, alphaChange);
    14. }
    This has not worked at all. How am I supposed to change the alpha?
     
  2. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    510
    Code (CSharp):
    1.     public Material myMaterial;
    2.     public float alphaChange = 1.0f;
    3.    
    4.     void Update()
    5.     {      
    6.         if (alphaChange > 0)
    7.             alphaChange -= 0.01f;
    8.    
    9.         myMaterial.color = new Color(0, 0, 0, alphaChange);
    10.     }
     
  3. CodeUnit07

    CodeUnit07

    Joined:
    Aug 10, 2023
    Posts:
    11
    Oh!!! So you use the 0 to 1 in the code. Not 0 to 255. Thanks zulo3d!
     
  4. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    yeah the 255 is for
    Color32
    ,
    Color
    uses 0.0-1.0.

    As far as I tried, modifying a
    Color32
    doesn't work, but
    Color
    always works just fine