I had the same problem, and I really appreciate this posting.
If anyone else has the same issues I did, I took 30 minutes to better understand this code, and I think I now get it.
To teach is to learn twice, so please see below my code for explanations (and let me know if I messed something up!):
public float fadeInTime; // must be declared up here instead of in the start below b/c this variable needs to be able to go in both start and update methods (can't be limited to just 1 of the 2). Try adding it to start and remove from here to see the error.
private Image fadePanel; // same as above
private Color currentColor = Color.black; //same as above. Also, Color here is not the 'color' element of the Image on our Side Panel gameObject, but rather a separate instance of the Color class.
We will assign our fadePanel in the start b/c GetComponent should only be called once (in Start instead of update) because it is a costly function for the CPU:
void Start()
{
fadePanel = gameObject.GetComponent<Image>(); // 1. Assigns the fadePanel as the Image component of the gameObject that this script is attached to.
}
Here is the important part – currentColor again is not the color of the Image component on the gameObject that our script is attached to. Instead, currentColor is a completely separate color that we are lowering the alpha in each step.
We then assign the completely separate currentColor to be the fadePanel’s color, changing the color of our Panel.
void Update()
{
if (Time.timeSinceLevelLoad < fadeInTime)
{
//Fade In
float alphaChange = Time.deltaTime / fadeInTime; // Setting this "/" operation as a variable, so that we can easily debug it later if needed (instead of debugging Time.deltaTime / fadeInTime each time, alphaChange is a bit easier to type.
currentColor.a -= alphaChange; //Here is the important part -- currentColor again is not the color of the Image component on the gameObject that our script is attached to. Instead, currentColor is a completely separate/different color instance that we are lowering the alpha of, in each step.
fadePanel.color = currentColor; // now we assign the completely separate currentColor to be the fadePanel's color, changing the color
// (Even though we are just changing the alpha, the resulting color is actually a new color -- Color is made of 4 elements: red, green, blue, and alpha; any change to the alpha means the color becomes a different color, just as adding more red or blue or green makes a color become a new color)
HAVING SAID all that, this lesson / video does not show the best way to do fades in general. A much better way to do fades is to use Canvas Groups instead of panels, as Canvas Groups are designed to fade in and still allow clicks (as well as it requires less code): CanvasGroup For Fading?
Hope that helps!
Blaine