Slowly fades from opaque to alpha

Hey guys, I’m trying to make a material slowly changes it opacity. It’s not working well because I only see my material when it’s totally opaque or totally transparent(I can’t see the fade effect) . Here’s the code. Can someone tell me what I’m doing wrong?

using UnityEngine;
using System.Collections;

public class alphaControl : MonoBehaviour {
	
	void Update () {
		
		
		if(Input.GetKeyUp(KeyCode.T)) {
			
			ToAlpha();
			
		}
		
		if(Input.GetKeyUp(KeyCode.F)) {
			
			fromAlpha();
			
		}
	
	}
	
	void ToAlpha () {
		
		float alpha = transform.renderer.material.color.a;
		
		while(alpha > 0) {
		
			alpha -= Time.deltaTime;
			print (alpha);
			Color newColor = new Color(1, 1, 1, alpha);
			transform.renderer.material.color = newColor;
			
		}
		
	}
	
	void fromAlpha () {
		
		float alpha = transform.renderer.material.color.a;
		
			while(alpha < 1) {
			
			alpha += Time.deltaTime;
			print (alpha);
			Color newColor = new Color(1, 1, 1, alpha);
			transform.renderer.material.color = newColor;
			
		}
		
	}
}

Any help would be appreciated!
Thanks from now.

Guto

Your code doesn’t make much sense since your loop is executed without delay. You might want to use a coroutine instead. Also there’s no need for two functions:

void Update ()
{
    if(Input.GetKeyUp(KeyCode.T))
    {
        StartCoroutine(FadeTo(0.0f, 1.0f));
    }
    if(Input.GetKeyUp(KeyCode.F))
    {
        StartCoroutine(FadeTo(1.0f, 1.0f));
    }
}

IEnumerator FadeTo(float aValue, float aTime)
{
    float alpha = transform.renderer.material.color.a;
    for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / aTime)
    {
        Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha,aValue,t));
        transform.renderer.material.color = newColor;
        yield return null;
    }
}

FadeTo will fade towards the value you pass in the time you specify. In the example above 1 sec.

If you want it to fade faster, just reduce the time:

StartCoroutine(FadeTo(1.0f, 0.5f));

A non code solution might be to use the animation editor to fade out the alpha. You are able to set a key frame from 0%, and for 100%, and it will handle the fade for you. (and if you set the animation to ping pong, once it reaches the end it will go backwards, and then start again)
Sorry I don’t know much about the programming side.