Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Resolved How to fade out object after some time on collision

Discussion in 'Scripting' started by bitlysub2anf, Jun 13, 2020.

  1. bitlysub2anf


    May 8, 2020
    Help I do not know how to change the color of the player gradually on collision to any object. I wrote a script and applied it to the player but it of course does what is say, but is limited to it.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    5. public class test : MonoBehaviour
    6. {
    7.     private void OnCollisionEnter2D(Collision2D collision)
    8.     {
    9.         GetComponent<SpriteRenderer>().color = new Color(255f, 255f, 255f, 0f); //Code works
    10.         Debug.Log("Collision"); //Collision is true
    11.     }
    12. }
    So, how do I make the alpha value (0f) decrease from 255 to 0 in 1-2 seconds?
    How do I build up the code?
    Thanks in advance
  2. PraetorBlue


    Dec 13, 2012
    So first off, let me just note that Color in Unity works a bit differently than you are expecting. The values in Color range from 0 to 1, not 0 to 255. (If you really prefer 0 to 255, there is a separate type you can use called Color32 which is effectively interchangeable with Color.

    Now that's out of the way, this is a perfect use case for a Coroutine using Color.Lerp:
    Code (CSharp):
    1. public class test : MonoBehaviour {
    2.     private void OnCollisionEnter2D(Collision2D collision) {
    3.         Debug.Log("Collision"); //Collision is true
    4.         StartCoroutine(FadeAlphaToZero(GetComponent<SpriteRenderer>(), 2f));
    5.     }
    7.     IEnumerator FadeAlphaToZero(SpriteRenderer renderer, float duration) {
    8.         Color startColor = renderer.color;
    9.         Color endColor = new Color(startColor.r, startColor.g, startColor.b, 0);
    10.         float time = 0;
    11.         while (time < duration) {
    12.             time += Time.deltaTime;
    13.             renderer.color = Color.Lerp(startColor, endColor, time/duration);
    14.             yield return null;
    15.         }
    16.     }
    17. }
    The coroutine will run every frame for the duration you give it, and it will gradually fade the alpha value of your sprite to 0 from wherever it started.
  3. bitlysub2anf


    May 8, 2020
    Works like a charm. Thank you very much (^∇^)
    I literary can imagine going through this searching the documentation for weeks, thinking code, watching tutorials. Phew, thank you once again.