Advertisement
noradninja

Color cycling example

Jul 18th, 2022
1,124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.12 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. /* This script expects a stadard color eg. Color or Albedo in the shader. Use Particles/Stadard Unlit for best results*/
  6.  
  7. public class General_Blinker : MonoBehaviour {
  8.  
  9.     public Color dimColor;
  10.     public Color midColor;
  11.     public Color brightColor;
  12.     public Color blinkerColor;
  13.     public Renderer objectRenderer;
  14.     public float repeatRate;
  15.     public bool blinkerOn;
  16.  
  17.     void OnEnable () {
  18.         objectRenderer = this.GetComponent<Renderer>(); //get renderer of object we are blinking
  19.     }
  20.     void OnDisable () {
  21.         blinkerOn = false; //disable blinking when object is enabled so we are only calling the routine loop once
  22.     }
  23.    
  24.     // Update is called once per frame
  25.     void Update () {
  26.         //only call this if blinkerOn is disabled, so we only run Blinker() once
  27.         if(!blinkerOn){
  28.             Blinker(dimColor, midColor, repeatRate);
  29.         }
  30.     }
  31.  
  32.     void Blinker(Color startColor, Color endColor, float duration){
  33.         blinkerOn = true;
  34.         StartCoroutine(colorAnimator(startColor, endColor, (repeatRate/4)));
  35.     }
  36.  
  37.     IEnumerator colorAnimator (Color startColor, Color endColor, float duration){
  38.         float time = 0;
  39.         while (time < duration){   
  40.                 blinkerColor = Color.Lerp(startColor, endColor, time/duration); //lerp the colors from dark to mid
  41.                 objectRenderer.material.SetColor("_Color", blinkerColor); //get the color of the material and set it to our current lerped value
  42.                 time += Time.deltaTime;
  43.                 yield return null;
  44.             }
  45.         StopCoroutine("colorAnimator");
  46.         blinkerColor = endColor; //make sure we have hit the target color so if/else block doesn't fail
  47.        
  48.         if (blinkerColor == midColor){
  49.            
  50.             StartCoroutine(colorAnimator(midColor, brightColor, repeatRate)); //call the routine again to lerp the color back from mid to bright
  51.         }
  52.         else if(blinkerColor == brightColor){
  53.             StartCoroutine(colorAnimator(brightColor, dimColor, repeatRate)); //call the routine again to lerp the color back from bright to dark
  54.         }
  55.         else if(blinkerColor == dimColor){
  56.             Blinker(dimColor, midColor, repeatRate); //if we are back at dark, rerun Blinker() to start the cycle again
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement