【问题标题】:Assign a random array string to a text component - Unity 4.6, uGUI将随机数组字符串分配给文本组件 - Unity 4.6,uGUI
【发布时间】:2015-07-09 22:20:04
【问题描述】:

我正在创建一个数组,其中包含我需要随机选择的描述(字符串)列表,然后分配给 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);
    }
}

【问题讨论】:

    标签: c# arrays random unity3d


    【解决方案1】:
    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;
    }
    }
    

    【讨论】:

      【解决方案2】:
      string myString = animalDescriptions[new Random().Next(animalDescriptions.Length)];
      

      您可能希望将 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()
      }
      

      【讨论】:

      • 我弹出了它,但在“Next”上出现错误:Assets/_Scripts/GameSetup.cs(23,67): error CS1061: Type UnityEngine.Random' does not contain a definition for Next' and no extension method可以找到Next' of type UnityEngine.Random'(您是否缺少 using 指令或程序集引用?)
      猜你喜欢
      • 1970-01-01
      • 2020-07-27
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 2017-08-20
      • 2021-12-07
      相关资源
      最近更新 更多