Unity C#循环一些文本而不重复它们

问题描述 投票:0回答:3

我在游戏主屏幕的底部有一条线,每次加载场景时,都会显示不同的提示(如何播放,如何更改音乐......)。

问题是我正在使用Random.Range但是,老实说,我更喜欢一种方式,所有提示都以随机的方式逐一显示,但不重复任何提示。

我的代码如下:

int randNum;
void Start () {
    randNum = Random.Range(0,5);
}

void Update () {

    switch (randNum)
    {
        case 0:
       // blah, blah, blah...
        case 1...

我怎样才能实现我的目标?

谢谢你的时间:)

c# random
3个回答
3
投票

您可以删除switch语句并将每条消息存储在列表中。

var tips = new List<string>();
tips.Add("The clouds are white");
...

然后你可以随机化列表中的元素(更多关于here)并逐一显示提示。您所需要的只是跟踪索引。例:

// This needs to be a field.
int index = 0;

void ShowTip() 
{ 
    // TODO: make sure index is not equal or greater than tips.Count

    tip = tips[index]; 
    index++; 

    // Display the tip
}

1
投票

你可以做的是洗牌提示清单。 Fisher-Yates shuffle是最常见的之一。

static Random _random = new Random();

static void Shuffle<T>(T[] array)
{
    int n = array.Length;
    for (int i = 0; i < n; i++)
    {
        // Use Next on random instance with an argument.
        // ... The argument is an exclusive bound.
        //     So we will not go past the end of the array.
        int r = i + _random.Next(n - i);
        T t = array[r];
        array[r] = array[i];
        array[i] = t;
    }
}

public static void Main()
{
        string[] array = { "tip 1", "tip 2", "tip 3" };
        Shuffle(array);
        foreach (string value in array)
        {
            Console.WriteLine(value);
        }
}

产量

net
dot
perls

source


1
投票

假设您的消息存储在全局级别声明的字符串列表中,并与您的随机类一起存储,并且其他字符串列表最初为空

List<string> needToDisplayMessages = new List<string>();
List<string> base_messages = new List<string>{"message1","message2","message3","message4","message5"};
Random rnd = new Random();

在您的更新方法中,检查要显示的消息列表是否为空,如果是,则使用预定义消息从列表中复制消息。现在使用随机实例选择要显示的消息的索引,并从动态列表中获取它。最后从仍待显示的消息列表中删除该消息。

void Update () {

    // We refill the list if it is empty
    if(needToDisplayMessages.Count == 0)
        needToDisplayMessages.AddRange(base_messages);

    // Choose a random number topped by the count of messages still to be displayed
    int index = rnd.Next(0, needToDisplayMessages.Count);

    string message = needToDisplayMessages[index];
    ..... display the message someway .....

    // Remove the message from the list
    needToDisplayMessages.RemoveAt(index);

}

当然,如果你想按顺序显示消息,则不需要这个,但(如已经说明的那样)只是一个索引。但是如果你想随机选择消息,直到你展示了所有这些消息,然后重新开始循环,那么这种方法也许并不复杂。

© www.soinside.com 2019 - 2024. All rights reserved.