How to fade out a game object using C#

I want to fade out a game object after pressing a key through C#.

Something like this:

    public GameObject obj;
        private bool canFade;
        private Color alphaColor;
        private float timeToFade = 1.0f;
    
        public void Start()
        {
            canFade = false;
            alphaColor = obj.GetComponent<MeshRenderer>().material.color;
            alphaColor.a = 0;
        }
        public void Update()
        {
            if (canFade)
            {
                obj.GetComponent<MeshRenderer>().material.color = Color.Lerp(obj.GetComponent<MeshRenderer>().material.color, alphaColor, timeToFade * Time.deltaTime);
            }
        }

Ok, so there is a way to do this using only code but it is alot more complicated. As an example, I have a menu here, and when I click on a button it will fade out then the scene will change. Screen capture - a6caa9bd06d4fc0a16457e934d67288c - Gyazo

To do this, you need to create an animation for the game object, via the animator. Choose the length of your animation, and make 2 keyframes - one at the start and one at the end. The keyframes should be the color of the gameobject, and under color you should see color - a. This is the alpha (or transparency) value. Make this value stay at its default at the start, and go to 0 at the end. Screenshot - 42c4969ab6fda9a3b9bb43211e1d02a0 - Gyazo In my example I made the RGB go to 0 too, as I have a black background.

In my code, it is triggered via a UI button press, but you can change that to be triggered on key press easily. This my code, which will trigger the animation and launch the next scene when the animation is done (after 1 second). You will need to re-arrange this code as I am a beginner at C# so it is very messy and probably quite slow, but you should be able to see the commands used relating to the animation.

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class MainMenuButtons : MonoBehaviour {
	private int switching = 0;
	private string mmscene2;
	private float timer = 1;
	private Animator fadeout;
	private Animator UIfadeout;
	public GameObject mmenufadeout;
	public GameObject mmfadeUI;
	public void MMBClicked (string mmbscene) {
		switching = 1;
		mmscene2 = mmbscene;
		mmenufadeout = GameObject.Find ("Menu");
		fadeout = mmenufadeout.GetComponent<Animator> ();
		UIfadeout = mmfadeUI.GetComponent<Animator> ();
		}
	void Update () {
		if (switching == 1) {
			fadeout.Play ("Menu_FadeOut");
			UIfadeout.Play ("MenuUIFadeOut");
			timer = timer - Time.deltaTime;
			if (timer <= 0) {
				SceneManager.LoadScene (mmscene2);
			}
		}
	}
}

For one, make sure the material’s Rendering Mode is set to FADE or nothing will happen.

Also, when looking at one of the other answers here I see what looks like an issue with the lerp which may be why some people are getting no effect when running the code. Take a look at the code in question here:

obj.GetComponent<MeshRenderer>().material.color = Color.Lerp(obj.GetComponent<MeshRenderer>().material.color, alphaColor, timeToFade * Time.deltaTime);

The problem here is that it is changing the startTarget of the lerp every frame. Think of a lerp like point A to point B. Using this with navigation, point A to point B doesn’t work if you keep changing point A around to equal the same place you are… That means you will always be at the start and never progress toward point B.

You need point A to stay fixed during the entire lerp. A lerp is simply progress from 0 to 100 percent. Understanding this can make lerps powerful. You can use them in interesting ways so keep in mind this is only one way to use them. People get creative and feed exponential time vales into the progress/target time field and get very smooth dampened results. You’ll have to do the work to figure that out for yourself though. But for now, here is the lerp flow you need.

:::In a single frame (same frame you want to start the lerp), get these values. To be clear, get them only at the start of the lerp.:::

float startTime
float targetTime
float startValue
float targetValue
bool running = true;

:::then use them like this::::

if(boolRunning)
{
    progress = Time.time - startTime;
    (thing to lerp) = (thing to lerp TYPE).Lerp(startValue, targetValue, progress/targetTime);

    if(progress >= targetTime)
    {
        boolRunning = false;
    }
}

:::In this case, for fading the alpha, you’d want to assign values like so:::

(thing to lerp) = obj.GetComponent<MeshRenderer>().material.color
(thing to lerp TYPE) = Color
startValue = obj.GetComponent<MeshRenderer>().material.color
targetValue = alphaColor

Anyhow, good luck. All the magic is here if you have the time to plug it in.

::

::

::

EDIT: Did the work so now you can have it all for fun and fancy free:

private void Update()
{
    if(Input.GetKeyDown(KeyCode.F))
    {
        StartCoroutine(Lerp_MeshRenderer_Color(value, value, value, value));
    }
}

private IEnumerator Lerp_MeshRenderer_Color(MeshRenderer target_MeshRender, float 
lerpDuration, Color startLerp, Color targetLerp)
{
    float lerpStart_Time = Time.time;
    float lerpProgress;
    bool lerping = true;

    while (lerping)
    {
        yield return new WaitForEndOfFrame();

        lerpProgress = Time.time - lerpStart_Time;

        if (target_MeshRender != null)
        {
            target_MeshRender.material.color = Color.Lerp(startLerp, targetLerp, lerpProgress / lerpDuration);
        }
        else
        {
            lerping = false;
        }
        
        
        if (lerpProgress >= lerpDuration)
        {
            lerping = false;
        }
    }

    yield break;
}