I want to fadein a UI image from transparent(alpha=0) to alpha=1, i thought my approach should be right, but it doesn't work, the image is not changing.
This is the code that i tried for doing that:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Fadein : MonoBehaviour {
public float FadeRate;
private Image image;
private float targetAlpha;
// Use this for initialization
void Start()
{
image = GetComponent<Image>();
Material instantiatedMaterial = Instantiate<Material>(image.material);
image.material = instantiatedMaterial;
targetAlpha = image.material.color.a;
Invoke("startFadein", 1);
}
IEnumerator FadeIn()
{
targetAlpha = 1.0f;
Color curColor = image.material.color;
while (Mathf.Abs(curColor.a - targetAlpha) > 0.0001f)
{
curColor.a = Mathf.Lerp(curColor.a, targetAlpha, FadeRate * Time.deltaTime);
image.material.color = curColor;
yield return null;
}
}
void startFadein()
{
StartCoroutine(FadeIn());
}
}
The image is not changing. But i tried fadeout by using this code, from 1 to 0, it just worked, i have no idea why the fadein doesn't work?