Display of lives using UI element/images

I realized through a comment on my block breaker-game, that I might not be the only one who struggled or is struggling to set up lives via UI elements/images instead of a text display, so I decided to share my code here. I based it on a youtube video (https://www.youtube.com/watch?v=LsUiJItfzxU).
Ok, on the LoseCollider script declare your sprites:

public GameObject image1, image2, image three3;// or less or more

In the code itself do the following…

 private void Start()
    {
       gameStatus = FindObjectOfType<GameStatus>();
       
            numLives = 3;
            image1.gameObject.SetActive(true);
            image2.gameObject.SetActive(true);
            image3.gameObject.SetActive(true);// if you have more lives, set all true in this section
           
       
    }
 private void OnTriggerEnter2D(Collider2D collision)
    {
        level = GameObject.FindObjectOfType<Level>();
        numLives--;
        if (numLives > 3)
            numLives = 3;
        switch (numLives)
        {
            case 3:
                image1.gameObject.SetActive(true);
                image2.gameObject.SetActive(true);
                imaget3.gameObject.SetActive(true);
                break;
            case 2:
                image1.gameObject.SetActive(true);
                image2.gameObject.SetActive(true);
                image3.gameObject.SetActive(false);
                break;

            case 1:
                 image1.gameObject.SetActive(true);
                 image2.gameObject.SetActive(false);
                 image3.gameObject.SetActive(false);
                break;

            case 0:
                image1.gameObject.SetActive(false);
                image2.gameObject.SetActive(false);
                image3.gameObject.SetActive(false);
                break;
        }

        if(numLives <0)
        {
            SceneManager.LoadScene("GameOver"); 
        }
        else
        {
            GameStatus.instance.CountLives(numLives);
            Ball.instance.SetBallPosition();
        }
        AudioSource.PlayClipAtPoint (deathSound, transform.position, 1f);
    }

On the GameStatus Script:

[SerializeField] int countLives;

and simply…

public void CountLives(int numLives)
    {
       
    }

…then hook all up in Unity .

It might not be the best way, but it worked for me. So I hope it can help out others who need it, or at least give an idea about how it can be done
cheers
Patricia

Privacy & Terms