How to lerp through colors for a sprite?
I'm trying to make my background, which is a sprite, smoothly change through the colors of the rainbow. I tried using GetComponent().color to just set one color but I can't even get that working. Can someone help me figure out what code is needed to iterate through colors smoothly?
Which component did you try to get? I believe the proper component to call for this is the SpriteRenderer. And what exactly isn't working? A bit of code would help! :) $$anonymous$$g. you can't change the components of GetComponent().color because they're get only. So you have to make a deepcopy of it and then apply the deepcopy (Color newCol = GetComponent().color; newCol.r = 1f; GetComponent().color = newCol;). Remember that the components (r,g,b,a) in Color range from 0-1 (and not 0-255).
to be more specific, color is a property handling a struct. aww the nature of a struct is being copied. that's why changing any value of it in one line is altering a copy that's never assigned back again.
Answer by Ahndrakhul · Feb 10, 2017 at 12:50 AM
I don't know if this will help you or not, but here's some code that kind of does what you want. It should work if you add it to the sprite. This example just lerps from blue to orange, but you can add as many colors to the list as you want.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorShift : MonoBehaviour
{
SpriteRenderer sRenderer;
float lerpTime = 4.0f;
List<Color> colors;
void Start ()
{
colors = new List<Color>() { Color.blue, new Color(1, .502f, 0) };
sRenderer = GetComponent<SpriteRenderer>();
}
void Update ()
{
if(Input.GetKeyUp(KeyCode.S))
{
StartCoroutine(ColorLerp());
}
}
IEnumerator ColorLerp()
{
if (colors.Count >= 2)
{
for (int i = 1; i < colors.Count; i++)
{
float startTime = Time.time;
float percentageComplete = 0;
while (percentageComplete < 1)
{
float elapsedTime = Time.time - startTime;
percentageComplete = elapsedTime / (lerpTime / (colors.Count - 1));
sRenderer.color = Color.Lerp(colors[i - 1], colors[i], percentageComplete);
yield return null;
}
}
}
}
}
Your answer
Follow this Question
Related Questions
Sprites/Cutout Shader ? 0 Answers
Shader invert sprite colors 2D 1 Answer
Acces shader color and lerp 1 Answer
Cover overlay sprites with geometry 0 Answers
How can I cast shadows onto sprites? 0 Answers