Last active
July 24, 2018 08:21
-
-
Save tpritc/3bef0c2ac4b53436c3a31567d334b0d4 to your computer and use it in GitHub Desktop.
Fade in GameObjects after a number of seconds. With nice curves.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
/// <summary> | |
/// This component fades the component in after a number of seconds. For it | |
/// to work, it needs to have a MeshRenderer, and the MeshRenderer needs a | |
/// material that lets you set the alpha, otherwise it totes won't work. | |
/// </summary> | |
[RequireComponent(typeof(MeshRenderer))] | |
public class FadeInAfterSeconds : MonoBehaviour { | |
/// <summary> | |
/// Time after level load to begin the fade in, in seconds. | |
/// </summary> | |
public float delayTime = 1.0f; | |
/// <summary> | |
/// The amount of time to go from the begining of the fade to its end, | |
/// in seconds. | |
/// </summary> | |
public float fadeInTime = 0.3f; | |
/// <summary> | |
/// The animation curve to follow, where the evaluated value is suppose | |
/// to be the alpha of the mesh. | |
/// </summary> | |
public AnimationCurve fadeInCurve; | |
/// <summary> | |
/// The mesh renderer we need to adjust the alpha of. It's set when the | |
/// component awakes. | |
/// </summary> | |
private MeshRenderer meshRenderer; | |
void Awake() { | |
// Grab the mesh renderer and cache it. | |
meshRenderer = GetComponent<MeshRenderer>(); | |
} | |
void Update() { | |
// Work out how far we are into the fade so far. | |
// NB: If the fade time is zero (or less), we use a super low | |
// number to make it seem like it's fading instantly. It's a bit of | |
// a hack, but it means no accidental divide-by-zero errors. | |
float amountIntoFade = 0 - ((delayTime - Time.timeSinceLevelLoad) / (fadeInTime > 0f ? fadeInTime : 0.001f)); | |
float curvedValue = fadeInCurve.Evaluate(amountIntoFade); | |
// Set the mesh renderer's color to its current color, but with the | |
// alpha from the curve. | |
meshRenderer.material.color = new Color(meshRenderer.material.color.r, meshRenderer.material.color.g, meshRenderer.material.color.b, curvedValue); | |
// If we've completed this fade, we can disable the component, | |
// since it won't be needed again. | |
if (Time.timeSinceLevelLoad > (delayTime + fadeInTime)) { | |
this.enabled = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Published under the Do What the Fuck You Want to Public License. Enjoy!