Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

button with random text

Discussion in 'Scripting' started by matstacy, Feb 6, 2020.

  1. matstacy

    matstacy

    Joined:
    Dec 10, 2019
    Posts:
    15
    Is there a way to make the text on the button show a different name everytime. for example i want to display a name, lets say Bob John. Is there a way i can press a button to make that name change to another if i do not want it.
    what i am trying to have is a random celebs name show up and i want to have 2 buttons, 1 that will get a new celebs name randomly from a list. and the other button will select the current celeb that is shown and take user to a new scene. any help at all will be great. Thankyou
     
  2. zurisar

    zurisar

    Joined:
    Nov 4, 2019
    Posts:
    24
    I'm not good in scripting, but for that in my mind best use enum variable

    Code (CSharp):
    1. public enum name
    2. {
    3.    "John Dow",
    4.    "Bob Dilah",
    5.    "Bill Smith"
    6. }
    7.  
    8. public int RandomNumber(int min, int max)
    9. {
    10.     Random random = new Random();
    11.     return random.Next(min, max);
    12. }
    13.  
    14. public string GetRandomName()
    15. {
    16. string result = (name)RandomNumber(0, Enum.GetNames(typeof(name)).Lenght)
    17. return result;
    18. }
     
  3. matstacy

    matstacy

    Joined:
    Dec 10, 2019
    Posts:
    15
    thanks heaps i will give it a try when i get home. thanks for your help
     
  4. matstacy

    matstacy

    Joined:
    Dec 10, 2019
    Posts:
    15
    Nah that code didnt work. thanks for your help anyway
     
  5. ZO5KmUG6R

    ZO5KmUG6R

    Joined:
    Jul 15, 2010
    Posts:
    490
    Something like this should do

    Code (CSharp):
    1. public class RandomButtonText : MonoBehaviour
    2. {
    3.  
    4. //texts list
    5. public string[] Texts = new string[]{"Hello", "World"};
    6.  
    7. //assign your button text in editor
    8. public UnityEngine.UI.Text ButtonText;
    9.  
    10. public void SetRandomButtonText()
    11. {
    12.     int textIndex = Random.Range(0, Texts.Length);
    13.     MyButtonText.text = Texts[textIndex];
    14. }
    15.  
    16. }