How do I swap the text within a button with another button's text?
I need to swap a button text with another button text. If Button1 contains "ABC" and Button2 contains "DEF", then after clicking Button1 and Button2 respectively, Button2 should contain "ABC" and Button1 should contain "DEF". I'm very green to Unity and C#. Any help is much appreciated!
Answer by rob5300 · Mar 28, 2017 at 11:05 AM
Like so:
//will require the namespace UnityEngine.UI
Button firstbutton;
Button secondbutton;
String firstbuttontext;
firstbuttontext = firstbutton.GetComponentInChildren<Text>.text;
firstbutton.GetComponentInChildren<Text>.text = secondbutton.GetComponentInChildren<Text>.text;
secondbutton.GetComponentInChildren<Text>.text = firstbuttontext;
What this does. We store the text from the first button, set the text of the first button to the second buttons text and finally set the set the text of the second button to the stored text of the first button.
You will want to declare that buttons as public variables outside of a method on your monobehaviour to be able to assign them in editor.
You could also change this to just work with the Text objects the buttons have as children, then you would be able to just use .text from them.
I would make a whole class but i wrote this on my phone, hope it actually works. Hope it helps!
Your answer
![](https://koobas.hobune.stream/wayback/20220612114128im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
instancing several buttons with different text 0 Answers
Several objects, same script, different values with no duplications 1 Answer
Dialogue Skipping Issues? 0 Answers
How to link up instantiated text in list to allow buttons to adjust number shown, c# 1 Answer
Swap 3D model with a button 2 Answers