简体   繁体   English

为文本组件分配随机数组字符串-Unity 4.6,uGUI

[英]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. 我正在创建一个包含描述(字符串)列表的数组,需要随机选择这些描述(字符串),然后分配给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. 您可能希望将该new Random()存储在其他位置,这样就不必每次都想要一个新的随机描述时就播下一个new Random() ,仅此而已。 You can do that by initializing your Random elsewhere, and simply using your instance of it in Start : 您可以通过在其他地方初始化Random并在Start简单使用它的实例来做到这一点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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