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. Dismiss Notice

randomly show text from a list

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

  1. matstacy

    matstacy

    Joined:
    Dec 10, 2019
    Posts:
    15
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class clicktochangetext : MonoBehaviour
    {
    private void PickRandomFromList()
    {
    string[] students = new string[] { "Harry", "Ron", "Hermione" };
    string randomName = students[Random.Range(0, students.Length)];
    print(randomName);
    }
    }
    [/code]

    I'm trying to have a text field display a random name from a array of strings. With a button that will change that Name to the next random name. I'm not sure if iam doing my onclick wrong or putting the script on the wrong object or if the script is wrong. I'm really new to unity and C# so any help would be great,thankyou.
     
  2. Team2Studio

    Team2Studio

    Joined:
    Sep 23, 2015
    Posts:
    98
    It's really hard to understand the problem if you do not tell us what the problem is...
    But since you are new to c# and Unity in general, I'll explain the steps to display
    a random array entry on a GUI object.

    - Change "private void PickRandomFromList" to "public void PickRandomFromList" (and read about the difference between those).
    - Create an empty GameObject and add your script to it. (Drag it on the GameObject or use the Add Component system).
    - Create a Canvas text object (Unity Text or TMPro Text) or 3d text object and make a reference to it in your script (name it "myTextField").
    - Create a Canvas Button and set it's OnClick event to be your PickRandomFromList method.
    - Change "print(randomName);" to "myTextField.text = randomName;"

    If you really want to make games (or apps) in Unity then I'd suggest you read the getting started guide from Unity.
     
    Haseebali4266 likes this.