簡體   English   中英

為文本組件分配隨機數組字符串-Unity 4.6,uGUI

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

我正在創建一個包含描述(字符串)列表的數組,需要隨機選擇這些描述(字符串),然后分配給gamobject中的文本組件。 我怎么做? 我已經創建了數組,但是我不知道從那里去哪里。 誰能幫我這個?

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)];

您可能希望將該new Random()存儲在其他位置,這樣就不必每次都想要一個新的隨機描述時就播下一個new Random() ,僅此而已。 您可以通過在其他地方初始化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