1
\$\begingroup\$

I have made a simple script, where I am changing image sprites by button click. I want to give an explanation for these images, so I am wanting to add text components for each sprite.

How to do that?

Here is what I made:

public class TutorialMenu : MonoBehaviour
{
    public List<Sprite> spriteCollection = new List<Sprite>();
    public Image original;
    public GameObject okButton;
    public GameObject startButton;

    private int m_spriteIndex = 0;
    private int m_spriteCount = 0;

    private void Start()
    {
        m_spriteCount = spriteCollection.Count;
        original.sprite = spriteCollection[m_spriteIndex];
    }

    public void NewImage()
    {
        m_spriteIndex++;
        if (m_spriteIndex == m_spriteCount)
        {
            m_spriteIndex = m_spriteCount -1;
            okButton.SetActive(false);
            startButton.SetActive(true);
        }
        original.sprite = spriteCollection[m_spriteIndex];
    }
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Something like this? Here we use a serializable struct to bundle together some text information with each sprite in the collection, and a TextMeshProUGUI component to display that text when the sprite is selected.

[System.Serializable]
public struct DescribedSprite {
    public Sprite sprite;
    public string description;
}

public List<DescribedSprite> spriteCollection;
public Image original;
public TextMeshProUGUI description;

public GameObject okButton;
public GameObject startButton;

private int m_spriteIndex = 0;

private void Start() {
    SelectSprite(m_spriteIndex);
}

public void NewImage() {
    if (m_spriteIndex < spriteCollection.Count - 1) {
        SelectSprite(m_spriteIndex + 1);
    } else {
        okButton.SetActive(false);
        startButton.SetActive(true);
    }
}

public void SelectSprite(int index) {
    m_spriteIndex = index;
    original.sprite = spriteCollection[index].sprite;
    description.text = spriteCollection[index].description;
}
\$\endgroup\$
1
  • \$\begingroup\$ Wow, thank you so much! This is exactly what I was looking for! \$\endgroup\$
    – imbruceter
    Jan 3 at 15:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .