Simple counter from 1 - 0, then back up to 1.

Hey all, I’m trying to make a simple counter that counts back from 1 to 0, and then counts back up to 1 again. I’ve made the counter variable a float as I’m attaching it the the alpha of a gameobject, so the object will fade in and out gradually. I’m sure I’m in the right ball park but I can’t seem to wrap my head around making it count up again! Here is the code I have so far.

Any help appreciated!


var box : GameObject;
var count : float = 1.0;
var whomp : AudioClip;
var fade = false;

function Update ()
{
	Debug.Log (count);
	if (fade == true && count > 0)
	{
		count = count -0.1 * Time.deltaTime * 7;
		box.renderer.material.color.a = count;
	}
	
	else if (count == 0)
	{
		count = count + 0.1 * Time.deltaTime * 7;
	}
}

function OnTriggerEnter()
{
	fade = true;
	audio.PlayOneShot(whomp);
}

This kind of behaviour can be achieved by storing the direction separately.

var direction = -1;

function Update () {
    Debug.Log (count);
    if (fade == true) {
        count += direction * Time.deltaTime * 0.7f;
        box.renderer.material.color.a = count;
    }
    if (count < 0 || count > 1) {
        direction *= -1;
    }
}

However in many cases it can be achieved using Mathf.PingPong().

box.renderer.material.color.a = Mathf.PingPong(Time.time * 0.7f, 1.0f);