how to change color of animated sprite prefab
I am making a 2D game in which there is a moving object just say like a cube. its more like a jelly cube moving ditto like jumping jelly.
I want to change the color of that "jelly cube" but not instantly but more like a filling like. it's need to start changing color from bottom to the top.
Please tell me any thing which could be helpful for this to me.
P.S. I am not really good at Unity right now maybe i am missing some basic things for this functionality please feel free for open comments anything related to this.
Answer by iwaldrop · Dec 19, 2016 at 08:49 AM
There's a couple ways of doing this, but probably the simplest for a beginner is to just use two sprites with exactly the same transform values; each having the colors that you want (start/finish).
The initial image would be set to Fill Origin Top and the final image to Bottom. At this point all you have to do is lerp the initial sprite's Fill Amount value from 0 -> 1 while simultaneously adjusting the ending sprite's value from 1 -> 0. It would look something like this.
This is just something I knocked together to demonstrate the concept. Change the color in the inspector and toggle the enabled flag to see what I mean. This script will duplicate the initial sprite and create a second one for you, destroying it when done. This isn't ideal if you're going to be doing a lot of this, but you should consider your use case and experiment with different solutions based on what kind of performance you get.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ColorFill : MonoBehaviour
{
public Color color;
public Image initial;
void OnEnable()
{
StartCoroutine(ChangeColor(color, 1));
}
public IEnumerator ChangeColor(Color color, float duration)
{
var final = Duplicate(initial);
final.color = color;
final.fillOrigin = 2;
float elapsed = 0;
while ((elapsed += Time.deltaTime) < duration)
{
var t = elapsed / duration;
initial.fillAmount = Mathf.Lerp(1, 0, t);
final.fillAmount = Mathf.Lerp(0, 1, t);
yield return null;
}
initial.fillAmount = 1;
initial.color = color;
Destroy(final.gameObject);
}
Image Duplicate(Image image)
{
var result = Object.Instantiate(image) as Image;
result.transform.SetParent(image.transform.parent, false);
result.transform.localScale = image.transform.localScale;
result.transform.position = image.transform.position;
result.transform.rotation = image.transform.rotation;
return result;
}
}
Btw, I might have misunderstood the question and made this example using a UI Image. If this is not what you want then the solution will be a bit more complicated. Post back with your use case. The best solution may be a shader or vertex manipulation. The UI stuff unity built has a bit more functionality out of the box than the Sprite does.