Jason Holt
Jason Holt

Reputation: 93

Changing Alpha value of image in Unity3D to create glowing effect

I have two images: one with a glowing border and one without. I want to create the effect of an image glowing by fading the glowing image in and out. My code:

private Image lightImage;
private float alpha;

// Use this for initialization
void Start ()
{

lightImage = GetComponent<Image>();
alpha = Time.deltaTime * 10;

}

void FixedUpdate()
{

// fade to transparent over 500ms.
lightImage.CrossFadeAlpha(0.0f, alpha, false);
// and back over 500ms.
lightImage.CrossFadeAlpha(1.0f, alpha, false);
}

I cannot seem to get it to work like I want (a slow transition over time.) It blinks in and out quickly but that is not the desired effect.

Upvotes: 0

Views: 204

Answers (1)

Harry
Harry

Reputation: 5707

  1. Replace: alpha = Time.deltaTime * 10; with alpha = 0.5f; And I think you should rename alpha variable to duration.
  2. You do not need to put CrossFadeAlpha in a FixedUpdate(). It is a tween. It does not need to be executed across multiple frames. Just put it in Start().
  3. Setting alpha to absolute 0 is not a good idea because sometimes, Unity treats 0 alpha objects as if they were disabled but I'm not sure. If you do run into this problem, set the alpha to a value very closed to 0 instead (0.004f for example).
  4. If you want it to fade out and then fade in, you should do it like this:

    IEnumerator Fade() { 
        // fade to transparent over 500ms.
        lightImage.CrossFadeAlpha(0.004f, 0.5f, false);
    
        // Wait for 500ms
        yield return new WaitForSeconds(0.5f); 
    
        // and back over 500ms.
        lightImage.CrossFadeAlpha(1.0f, 0.5f, false);
    }
    
    void Start() {
        StartCoroutine(Fade());
    }
    

Upvotes: 1

Related Questions