Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Easiest Way To Control (Transparency Pulse)

Discussion in 'Scripting' started by GoodNight9, Apr 22, 2021.

  1. GoodNight9

    GoodNight9

    Joined:
    Dec 29, 2013
    Posts:
    123
    Hello! I was wondering what would be the simplest/most effecient way to program the transparency of a button to pulse back and fourth between .4 and 1?? If possible, it would also be nice to control the speed bounces back and fourth as well. Here's what I got for a start:


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class ButtonTest : MonoBehaviour
    7. {
    8.     public Image buttonImage;
    9.     public float transparency;
    10.  
    11.     void Update()
    12.     {
    13.         buttonImage.color = new Color(1,1,1,transparency);
    14.         //Alpha goes back and fourth between 0 and 1 constantly
    15.     }
    16. }
    Thank you for your time!
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    If you want to really control it, consider using an AnimationCurve. You can design the curve in the editor and read it in your code with AnimationCurve.Evaluate for the current time.

    As for simple code based methods, look at Mathf.PingPong and of course, the classic Mathf.Sin.
     
    GoodNight9 likes this.
  3. GoodNight9

    GoodNight9

    Joined:
    Dec 29, 2013
    Posts:
    123
    That pingpong thing was JUST what I needed. How would I augment this, so that it doesn't go down to 0, but instead goes to .3?? I got this so far, but it goes ABOVE 1, and I don't want that :(

    Code (CSharp):
    1. public class ButtonTest : MonoBehaviour
    2. {
    3.     public Image buttonImage;
    4.     public float transparency;
    5.     public float changeSpeed;
    6.  
    7.  
    8.     void Update()
    9.     {
    10.         buttonImage.color = new Color(1,1,1,transparency);
    11.         transparency = Mathf.PingPong((Time.time) * changeSpeed, 1) + .3f;
    12.     }
    13. }
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Code (CSharp):
    1. float pingpong = Mathf.PingPong((Time.time) * changeSpeed, 1);
    2. transparency = Mathf.Lerp(.3f, 1f, pingpong);
     
    j_henry and GoodNight9 like this.
  5. GoodNight9

    GoodNight9

    Joined:
    Dec 29, 2013
    Posts:
    123
    THANKYOU!!!! This is code is perfect for me, my question has been answered-!

    Much appreciated Praetor-!
     
    PraetorBlue likes this.