Created
September 3, 2012 22:04
-
-
Save markusrt/3613941 to your computer and use it in GitHub Desktop.
Unity Script: Fade Orthello sprite in or out
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; | |
using System.Collections; | |
public class FadeSprite : MonoBehaviour { | |
public enum FadeDirection { FadeOut, FadeIn } | |
public FadeDirection Direction = FadeDirection.FadeOut; | |
public float Speed = 0.0f; | |
public bool Loop; | |
private OTSprite sprite; | |
private float CurrentDirection | |
{ | |
get { return Direction == FadeDirection.FadeOut ? -1.0f : 1.0f; } | |
} | |
void Start () | |
{ | |
sprite = gameObject.GetComponent<OTSprite>(); | |
if(sprite == null) | |
{ | |
Debug.LogWarning("FadeSprite script only works with orthello sprites"); | |
} | |
} | |
void Update () | |
{ | |
if (sprite == null) | |
{ | |
return; | |
} | |
ChangeAlpha (); | |
CheckLoopCondition (); | |
} | |
private void ChangeAlpha () | |
{ | |
sprite.alpha += Time.deltaTime * Speed * CurrentDirection; | |
} | |
void CheckLoopCondition () | |
{ | |
var fadeOutCompleted = sprite.alpha < 0.0f; | |
bool fadeInCompleted = sprite.alpha > 1.0f; | |
if( Loop && ( fadeOutCompleted || fadeInCompleted ) ) | |
{ | |
ToggleFadeDirection(); | |
} | |
if( !Loop && fadeOutCompleted ) | |
{ | |
Destroy(gameObject); | |
} | |
} | |
private void ToggleFadeDirection() | |
{ | |
Direction = Direction == FadeDirection.FadeOut | |
? FadeDirection.FadeIn : FadeDirection.FadeOut; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment