使用 c# 加载随机场景而不重复 [英] Load random scenes without repetition using c#

查看:59
本文介绍了使用 c# 加载随机场景而不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 c# 随机加载场景而不重复.任何帮助都可以.谢谢.

I want to load scenes randomly without repetition using c#. Any help would do. Thanks.

int[] array = new int[] { 1, 2, 3, 4, 6, 8, 9, 10, 11, 12 };
List<int> list = new List<int>();

void Start()
{
    list.AddRange(array);
}

int GetUniqueRandom(bool RemoveFromTheList)
{
    if (list.Count == 0)
    {
        if (RemoveFromTheList)
        {
            list.AddRange(array);
        }
        else
        {
            return -1; // never repeat
        }
    }

    int rand = Random.Range(0, 10);
    int value = list[rand];
    list.RemoveAt(rand); return value;
}

推荐答案

一个干净的好方法是打乱数组,然后将所有元素放在一个堆栈中.获取随机元素所需要做的就是从堆栈中弹出一个项目.

A nice clean way is to shuffle the array, then put all the elements in a stack. All you need to get a random element is to pop an item off the stack.

您将要删除字段列表中的列表并替换为这个;

You will want to remove the list in the list of fields and replace with this;

Stack remainingScenes = new Stack();

删除 Start() 方法的内容 - 您不需要它.

Remove the content of the Start() method - you don't need it.

在您获取新号码的方法中;

In your method to get a new number;

if (remainingScenes.Count == 0) {
    int n = array.Length;
        while (n > 1) 
        {
            int k = rng.Next(n--);
            T temp = array[n];
            array[n] = array[k];
            array[k] = temp;
        }

        foreach(var element in array) { 
             remainingScenes.Push(element);
        }
}

return remainingScenes.Pop();

shuffle 方法是从这里.

The shuffle method is from here.

这篇关于使用 c# 加载随机场景而不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆