Search code examples
c#unity-game-enginebackground

Change Background images smoothly in Unity2d


I have 12 background images which are a little bit different from each other and I need to have smooth transitions while changing, it shouldn't be a distraction for a player. my code:

   IEnumerator changeBackground(){
        while (true){
            x = Random.Range(0,12);
            background.sprite = Sprites[x];
            yield return new WaitForSeconds(5f);
        }
    }

Solution

  • As mentioned you probably won't come around having two overlayed images and fade.

    To make it easy you could use a forth and back fading of a single image while the other stays always opaque and do e.g.

    public Image background;
    public Image backgroundFade;
    public float fadeDuration = 1f;
    
    private readonly Color _fadeStartColor = new Color(1, 1, 1, 0);
    
    IEnumerator changeBackground()
    {
        while (true)
        {
            x = Random.Range(0,12);
    
            backgroundFade.sprite = Sprites[x];          
            backgroundFade.color = _fadeStartColor;
            backgroundFade.gameObject.SetActive(true);
    
            for(var timePassed = 0f; timePassed < fadeDuration; timePassed += Time.deltaTime)
            {
                backgroundFade.color = Color.Lerp(fadeStartColor, Color.white, timePassed / fadeDuration);
                yield return null;
            }
    
            background.sprite = Sprites[x];
            backgroundFade.gameObject.SetActive(false);
    
            yield return new WaitForSeconds(5f);
        }
    }
    

    Now you simply need to create an image as child of your background and make it stretch to the full size of the background. Then make it initially inactive and reference it into backgroundFade