Search Unity

Change The Alpha Of A Button In C# Script?

Discussion in 'UGUI & TextMesh Pro' started by JeZxLee, Aug 12, 2018.

  1. JeZxLee

    JeZxLee

    Joined:
    Jul 24, 2016
    Posts:
    222
    Hi,

    I am trying to change the alpha of a button in C# script.
    Is the above possible, if yes then please provide an example...
    Thanks!

    Jesse
     
  2. JeZxLee

    JeZxLee

    Joined:
    Jul 24, 2016
    Posts:
    222
  3. JeZxLee

    JeZxLee

    Joined:
    Jul 24, 2016
    Posts:
    222
    Here is the script I have attached to the button(it compiles, but does nothing?):
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class ScreenFadeScript : MonoBehaviour {
    5.    // Use this for initialization
    6.    void Start () {
    7.        Globals.ScreenFadeAlpha = 255;
    8.        Globals.ScreenFadeStatus = Globals.ScreenFadingIn;
    9.    }
    10.    // Update is called once per frame
    11.    void Update () {
    12.        if (Globals.ScreenFadeStatus == Globals.ScreenFadingIn)
    13.        {
    14.            if (Globals.ScreenFadeAlpha > 0)
    15.            {
    16.                Globals.ScreenFadeAlpha-=1;
    17.                Color tmp = GetComponent<UnityEngine.UI.Image>().color;
    18.                tmp.a = Globals.ScreenFadeAlpha;
    19.                GetComponent<SpriteRenderer>().color = tmp;
    20.            }
    21.        }
    22.    }
    23. }
    24.  
     
  4. Hosnkobf

    Hosnkobf

    Joined:
    Aug 23, 2016
    Posts:
    1,096
    hi,

    please not that the Color struct is using float values, not bytes.
    For Alpha it means:
    - a value of 0 is invisible
    - a value of 1 is opaque
    - everything greater than 1 is clamped to one.