HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Pulsing Alpha Channel

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
alphachannelpulsing

Problem

The following script makes an image pulse in Unity by fluctuating its alpha channel. However, I feel like there is a lot of duplicate code in the update method. How can I clean up that code to have it not repeat itself with +-, true false, etc.?

using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class Pulse : MonoBehaviour
{
    private Image image;

    [Tooltip("How long in seconds it takes to complete a pulse")]
    [SerializeField]
    [Range(0.0f, 60.0f)]
    private float time = 2.0f;

    [Tooltip("Minimum alpha to pulse to")]
    [SerializeField]
    [Range(0.0f, 1.0f)]
    private float minAlpha = 0.0f;

    [Tooltip("Maximum alpha to pulse to")]
    [SerializeField]
    [Range(0.0f, 1.0f)]
    private float maxAlpha = 1.0f;

    private bool alphaIncreasing = false;

    private void Awake()
    {
        image = GetComponent();
    }

    void Update()
    {
        var color = image.color;
        float alphaChange = Time.deltaTime / time / 2.0f;
        if (alphaIncreasing)
        {
            color.a += alphaChange;
            if (color.a >= maxAlpha)
            {
                color.a = maxAlpha;
                alphaIncreasing = false;
            }
        }
        else
        {
            color.a -= alphaChange;
            if (color.a <= minAlpha)
            {
                color.a = minAlpha;
                alphaIncreasing = true;
            }
        }
        image.color = color;
    }
}

Solution

Everything can be controlled by a changing limit.

The (2 * limit - 1) results in either 1 for limit 1 or -1 for limit 0 controlling whether you are increasing or decreasing.

color.a * sign >= limit if limit = 1 and color.a > 1 or limit = 0 and color.a < 0

and maxAlpha - limit is either 1 if limit is 0 or 0 if limit is 1

Remove

private float minAlpha = 0.0f;

private bool alphaIncreasing = false;


Add

private float limit = 0.0f;


New Update code.

void Update()
{
    var color = image.color;
    float alphaChange = Time.deltaTime / time / 2.0f;
    var sign = 2 * limit - 1;
    color.a += sign * alphaChange;
    if (color.a * sign >= limit)
    {
        color.a = limit;
        limit = maxAlpha - limit;
    }
    image.color = color;
}

Code Snippets

private float minAlpha = 0.0f;

private bool alphaIncreasing = false;
private float limit = 0.0f;
void Update()
{
    var color = image.color;
    float alphaChange = Time.deltaTime / time / 2.0f;
    var sign = 2 * limit - 1;
    color.a += sign * alphaChange;
    if (color.a * sign >= limit)
    {
        color.a = limit;
        limit = maxAlpha - limit;
    }
    image.color = color;
}

Context

StackExchange Code Review Q#155069, answer score: 4

Revisions (0)

No revisions yet.