How to change image sprite with text multiple times with button?
What I want is, when I click on the button, the image and it's child object (text component) will change to a next image sprite and text component. I tried to do that with switch statement but I'm unsure that this is the right solution and I also managed to do that for the text only, but not the image. And I'm also linking the buttons child object instead which is not ideal
Here's what I've done:
     public Button nextButton;
     private string currentText = "Text1";
 
     void Start()
     {
         SetText(currentText);
         nextButton.onClick.AddListener(MyButtonClick);
     }
 
     void MyButtonClick()
     {
         switch (currentText)
         {
             case "Text1":
                 currentText = "Text2";
                 SetText(currentText);
 
                 break;
 
             case "Text2":
                 currentText = "Text3";
                 SetText(currentText);
                 break;
 
             case "Text3":
                 currentText = "Play Game";
                 SetText(currentText);
                 break;
         }
     }
 
     void SetText(string text)
     {
         nextButton.transform.GetChild(0).GetComponent< TMPro.TextMeshProUGUI>().text = text;
     }
Thank you in advance!
Answer by Hellium · Jan 02 at 07:38 PM
 [System.Serializable]
 public struct CaptionedImage
 {
      [SerializeField] private Sprite sprite;
      [SerializeField] private string caption;
 
     public void Apply(Image image, TMPro.TextMeshProUGUI text)
     {
          image.sprite = sprite;
          text.text = caption;
      }
 }
  [SerializeField] private Button nextButton;
  [SerializeField] CaptionedImage[] captionedImages;
  private Image image;
  private TMPro.TextMeshProUGUI text;
  private int index;
 
  void Start()
  {
      image = nextButton.GetComponent<Image>();
      text = nextButton.transform.GetChild(0).GetComponent<TMPro.TextMeshProUGUI>();
      nextButton.onClick.AddListener(() => ApplyCaptionedImage((index + 1) % captionedImages.Length));
      ApplyCaptionedImage(0);
  }
 
  void ApplyCaptionedImage(int i)
  {
      index = i;
      captionedImages[index].Apply(image, text);
  }
Your answer
 
 
             Follow this Question
Related Questions
Can anybody tell me how to display text on axis? 1 Answer
[SOLVED]My UI text don't update from script 3 Answers
UI Text: Words at end of line jumping to next line 0 Answers
My Unity.exe deleted (Unity 2019.3.11),My Unity.exe was deleted (Unity 2019.3.11) 0 Answers
[Help] I keep getting an error with blank message when I create a C# script. 3 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                