Good day.

There is a button and a window. When you click on a button, the window changes its transparency. How to make the change in the degree of transparency was smooth?

public GameObject AlphaObj; public Image AlphaImage; private int AlphaCheck = 0; void Update() { AlphaImage = AlphaObj.GetComponent<Image>(); } public void OpenClose() { if (AlphaCheck == 0) { AlphaImage.color = new Color(AlphaImage.color.r, AlphaImage.color.g, AlphaImage.color.b, AlphaImage.color.a + 1.0f); AlphaCheck = 1; } else { AlphaImage.color = new Color(AlphaImage.color.r, AlphaImage.color.g, AlphaImage.color.b, AlphaImage.color.a - 1.0f); AlphaCheck = 0; } } 

As an option, I can push the change of transparency in Update with the addition of Time.deltaTime, and in OpenClose, leave the change in the check value. But perhaps there is an option without overloading such a trifle Update'a.

    2 answers 2

    1. AlphaImage = AlphaObj.GetComponent<Image>(); code AlphaImage = AlphaObj.GetComponent<Image>(); severely affects performance if it is not done in Start() or Awake() . And the more so it makes no sense to do on every frame in the update.
    2. For your task, I advise you to use the LeanTween library or its analogs like iTween. There are a lot of useful pieces, including a smooth change of parameters. For example:

        var time = 2.0f; var alphaVal = 0.0f; LeanTween.alpha(gameObject, alphaVal, time); 
    • For a twin +1, it’s time to introduce the label IMHO, there are quite a lot of questions lately with him. - RiotBr3aker

    For me, such things are better done through a standard animator. To him, write a small controller that updates the parameters at the command from the button and the animation starts. Here is an example video in English how to do.

    • As for me - it's too fat for such a simple animation - RiotBr3aker
    • But the process of managing the process costs a minimum of code. The animation controller allows you to customize the state of the machine and the designer can edit it, without bothering about what you put in your code. In my applications in this way I made the animation of the appearance of the window, closure, and no one bothers to make the animation more complex and entertaining, and you can’t fix what is written in the code. - KingPeas 5:44 pm
    • Option certainly working and well extensible, but IMHO - overkil for this task. - RiotBr3aker