简体   繁体   中英

Assign a random array string to a text component - Unity 4.6, uGUI

I'm creating an array with a list of descriptions (strings) that I need to choose randomly and then assign to a text component in a gamobject. How do I do that? I've created the array but I don't know where to go from there. Can anyone help me with this?

public string[] animalDescriptions = 
{
    "Description 1",
    "Description 2",
    "Description 3",
    "Description 4",
    "Description 5",
};


void Start () 
{

    string myString = animalDescriptions[0];
    Debug.Log ("You just accessed the array and retrieved " + myString);

    foreach(string animalDescription in animalDescriptions)
    {
        Debug.Log(animalDescription);
    }
}
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Test : MonoBehaviour 
{
public Text myText;

public string[] animalDescriptions = 
{
    "Description 1",
    "Description 2",
    "Description 3",
    "Description 4",
    "Description 5",
};

void Start()
{
    string myString = animalDescriptions [Random.Range (0, animalDescriptions.Length)];
    myText.text = myString;
}
}
string myString = animalDescriptions[new Random().Next(animalDescriptions.Length)];

You might want to store that new Random() somewhere else so that you don't seed a new one every time you want a new random description, but that's about it. You can do that by initializing your Random elsewhere, and simply using your instance of it in Start :

Random rand = new Random();
// ... other code in your class
void Start()
{
    string myString = animalDescriptions[rand.Next(animalDescriptions.Length)];
    // ... the rest of Start()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM