- Home /
How to replace Button Text when clicking another button?
Hello,
I'm using Unity 4.6 and new to both Unity and c#.
How would I go about replacing the text within a button with the text from another button?
Say I have 5 buttons, the first button would be the main one that gets updated. I would like the text within that button to be replaced with the text from whichever other button the user clicks. So if I were to click Button 4 that says Fish, Button 1 would then also say Fish. Then if i were to click a different button it would update again to the text of the last button clicked. Example below.
Button 1: TempText
Button 2: Dog
Button 3: Bird
Button 4: Fish
Button 5: Bear
I've watched the tutorials and read other Unity answers on how to do this with the score, but as I'm new to this I'm not sure how to adapt it to work with clicking on a button to update another button. Would someone be kind enough to link me to a tutorial that explains how to do this or maybe provide example c# code?
Thank you for your time and assistance. I apologize ahead of time if there is a resource explaining exactly this, I haven't had luck finding it.
Answer by jenci1990 · Dec 05, 2014 at 12:50 PM
Select your "Dog" button and add OnClick event:
Drop your TextObject to it:
....
Select from the functions the "Text/string text" component.
4.and set the new name:
You can do it in the other buttons.
Thank you very much! I was trying to figure out how to do it with the On Click events at first but couldn't get it. I've marked this as Answered as it does what I want, I appreciate that. Curious, is there a way to auto populate the text rather than having to type the string for each one? Just trying to think of how to save time if this was done on a much larger scale. For now I don't $$anonymous$$d doing it as it fulfills my needs. Again, thank you for your time and assistance on this, much appreciated.
You can do it by script. This scrip change the target Text to the button name automatically. Add this script to all button (except the contolled button), and assign the "targetText" variable.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class SetButtonText : $$anonymous$$onoBehaviour {
public Text targetText;
private Button myButton;
void OnEnable() {
myButton = GetComponent<Button>();
myButton.onClick.AddListener(() => {ChangeTarget();});
}
void ChangeTarget() {
string myString = GetComponentInChildren<Text>().text;
targetText.text = myString;
}
}
Very cool. Thank you so much for going out of your way to show me how to do this. =)
Your answer
Follow this Question
Related Questions
Canvas Button persistence 0 Answers
v4.6 Create GUI Elements Via Script? 1 Answer
How do I access the button component of a button in the new gui system. 2 Answers
Text isn't showing up on button 0 Answers