Fading sprite issue

I’m trying to get a sprite to fade in and out continuously. The script I have makes the sprite start visible and fade out but then it never fades back in.

I have this script on the sprite:

using UnityEngine;
using System.Collections;

public class TapToStart : MonoBehaviour {

public float minimum = 0.0f;
public float maximum = 1f;
public float duration = 5.0f;
private float startTime;
public bool fade;
public SpriteRenderer sprite;

void Start() {
startTime = Time.time;
fade = true;
}

void Update() {
	if(fade)
	{
		float t = (Time.time - startTime) / duration;
		sprite.color = new Color(1f,1f,1f,Mathf.SmoothStep(minimum, maximum, t));
		fade = false;
	}
	if(!fade)
	{
		float t = (Time.time - startTime) / duration;
		sprite.color = new Color(1f,1f,1f,Mathf.SmoothStep(maximum, minimum, t));
		fade = true;
	}
}
}

If anyone knows how to fix this issue, it would be very helpful.

You have some problems in your logic. That is, each time through the loop, it executes both the ‘fade’ code and the ‘!fade’. Using this kind of logic, you don’t want to set ‘fade’ to false until this value:

  float t = (Time.time - startTime) / duration;

is at or above 1.0. likewise you don’t want to set it to true until the value is 0.0 or below.

But this is the long way for this functionality. Here is a bit of code that fades in and out:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
	
	public float duration = 5.0f;
	public SpriteRenderer sprite;

	void Update() {
		float a = Mathf.PingPong (Time.time / duration, 1.0f);
		sprite.color = new Color(1f, 1f, 1f, a);
	}
}