Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by SimonClintonIv · Aug 17, 2016 at 03:56 PM · alphafadeout

How to fade out a game object using C#

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

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SimonClintonIv · Aug 19, 2016 at 07:53 AM 0
Share

Nun of the code is working for me I don't $$anonymous$$now where I am going wrong.

4 Replies

· Add your reply
  • Sort: 
avatar image
4

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);
             }
         }
 
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image isteffy · Jan 25, 2017 at 11:16 AM 1
Share

This does nothing for me :(

avatar image Ed-Den-Gaming · May 27, 2020 at 03:09 PM 0
Share

I changed the to just Renderer and it worked

avatar image
2

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);
             }
         }
     }
 }
 
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
2

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;
 }
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image BobbaPB · Mar 15, 2021 at 08:44 AM 0
Share

Where do I define target_Meshrenderer and lerpDuration? I get errors that they don't exist in the current context.

avatar image SpaceManDan BobbaPB · Mar 15, 2021 at 09:25 PM 0
Share

!!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.

avatar image
1

Answer by EDevJogos · Jan 25, 2017 at 01:02 PM

http://answers.unity3d.com/questions/992672/fade-gameobject-alpha-with-standard-shader.html

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

58 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges