- Home /
How to fade out a game object using C#
I want to fade out a game object after pressing a key through C#.
Nun of the code is working for me I don't $$anonymous$$now where I am going wrong.
Answer by Mukabr · Aug 17, 2016 at 06:11 PM
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);
}
}
Answer by Legion_Game_Studios · Aug 17, 2016 at 08:39 PM
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. https://gyazo.com/a6caa9bd06d4fc0a16457e934d67288c
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. https://gyazo.com/42c4969ab6fda9a3b9bb43211e1d02a0 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);
}
}
}
}
Answer by SpaceManDan · Jan 20, 2018 at 02:34 PM
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;
}
Where do I define target_Meshrenderer and lerpDuration? I get errors that they don't exist in the current context.
!!For one, make sure the material's Rendering Mode is set to FADE or nothing will happen!!
You'll need to use some kind of GetComponent() on the object with the mesh renderer you need to store. For example:
MeshRenderer myMeshRenderer = GetComponent();
or
MeshRenderer myMeshRenderer = this.GetComponent<MeshRenderer>();
Both should produce the same result. If this script is on the object you want to fade then it will find the correct meshRenderer.
Then, lerpDuration is anything you want it to be in seconds. For example.
float myLerpDuration = 5f; //this equals 5 seconds
Then you'll need the end result you're looking for. For example:
Color myEndColor = new Color(myMeshRenderer.material.color.r, myMeshRenderer.material.color.g, myMeshRenderer.material.color.b, 0f);
Finally, you would call this function in Update like so.
StartCoroutine(Lerp_MeshRenderer_Color(myMeshRender, myLerpDuration, myMeshRenderer.material.color, myEndColor));
Basically all this is in my first instruction so if you get lost, read what I wrote in the first post as the details are explained in there.
Your answer
Follow this Question
Related Questions
Changing a GUITexture's alpha gives me no effect in game. 0 Answers
alpha value not changing(gradual decrease) during runtime 1 Answer
Pain Screen Flash UI and fades 1 Answer
How to make a float incrementally go up, reach the top, then go back down again and stop 1 Answer
Lerp doesn't work with SetAlpha 1 Answer