1
\$\begingroup\$

I'm trying to create a way in which if I press a button, it'll highlight other objects whilst at the same time fading other objects. I also have other buttons that will fade and highlight different objects. Some of which may have been modified by the first button.

I had done this originally in a really dumb way like so

public void Highlight()
{
    foreach (Image image in imagesToHighlight)
    {
        Color c = image.color;
        if(c.a < maxColor)
        {
            c.a = maxColor;
        }

        image.color = c;
    }

    foreach (Image image in imagesToFade)
    {
        Color c = image.color;
        if(c.a > halfColor)
        {
            c.a = halfColor;
        }
        image.color = c; 
    }
}

This works, but I was wanting it to happen gradually to provide a smother transition. I managed to get the fade working, by changing the code to this:

IEnumerator Fade(Image image)
{
    float elapsedTime = 0.0f;
    Color c = image.color;
    while (elapsedTime < 1)
    {
        yield return fadeInstruction;
        elapsedTime += Time.deltaTime;
        c.a = 1.0f - Mathf.Clamp01 (elapsedTime / fadeTime);
        image.color = c;
    }
}

I then call the method in my foreach loop like so:

foreach (Image image in imagesToFade)
{
    StartCoroutine (Fade (image));
}

Again, this works fine. The problem I'm having is checking to see if the image is faded, and if it is and needs to be highlighted, it reverses from the fade value to the highlight value (0.5 to 1.0).

I thought this would be a simple change as did this

IEnumerator HighLight(Image image)
{
    float elapsedTime = 0.0f;
    Color c = image.color;


    while (elapsedTime < 1 )
    {
        yield return fadeInstruction;
        elapsedTime += Time.deltaTime;

        c.a +=  Mathf.Clamp01 (elapsedTime / fadeTime);

        image.color = c;
    }
}

Simply changing the alpha line. However, now my image alphas jump all of the place in the highlight method. I'm at a loss as to how I can fix this. Can someone please tell me what I'm doing wrong?

\$\endgroup\$
  • \$\begingroup\$ So you want to start fading in and out from that very alpha value it actually has? Like if alpha is 1 then it should first gradually go to 0 and 1 so on.. and if alpha is 0.6 then on highlight it should go first to 1 and then 0. Something like that? \$\endgroup\$ – Hamza Hasan Oct 4 '16 at 13:17
  • \$\begingroup\$ You'll want to use Mathf.Lerp: docs.unity3d.com/ScriptReference/Mathf.Lerp.html \$\endgroup\$ – Jesse Williams Oct 4 '16 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.