unity3d 以相同顺序随机播放

bnlyeluc  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(137)

我有一个精灵列表和字符串列表。我想对它们进行随机播放。随机播放的效果不同,但对精灵和字符串都是如此。随机播放的顺序可以相同吗?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ShuffleList : MonoBehaviour
{
    public List<Sprite> iconSprite = new List<Sprite>();
    public List<string> priceText = new List<string>();

    // Start is called before the first frame update
    void Start()
    {
        iconSprite.Shuffle();
        priceText.Shuffle();
    }

}

public static class IListExtensions {
    /// <summary>
    /// Shuffles the element order of the specified list.
    /// </summary>
    public static void Shuffle<T>(this IList<T> ts) {
        var count = ts.Count;
        var last = count - 1;
        for (var i = 0; i < last; ++i) {
            var r = UnityEngine.Random.Range(i, count);
            var tmp = ts[i];
            ts[i] = ts[r];
            ts[r] = tmp;
        }
    }
}
k4emjkb1

k4emjkb11#

你需要一次对两个列表进行洗牌,所以不要使用只有一个参数的extension-method,而应该使用一个有两个列表作为参数的普通方法。

public static void Shuffle<T1, T2>(IList<T1> list1, IList<T2> list2) 
{
    var count = ts.Count;
    var last = count - 1;
    for (var i = 0; i < last; ++i) {
        var r = UnityEngine.Random.Range(i, count);
        var tmp1 = list1[i];
        var tmp2 = list2[i];
        list1[i] = list1[r];
        list1[r] = tmp1;
        list2[i] = list2[r];
        list2[r] = tmp2;
    }
}

或者,您也可以为random-generator使用相同的种子,这将导致生成相同的序列:

public static void Shuffle<T>(this IList<T> ts, long seed) 
{
    UnityEngine.Random.InitState(seed);
    var count = ts.Count;
    var last = count - 1;
    for (var i = 0; i < last; ++i) {
        var r = UnityEngine.Random.Range(i, count);
        var tmp = ts[i];
        ts[i] = ts[r];
        ts[r] = tmp;
    }
}

现在,您可以为函数的两个调用提供相同的种子,例如:

void Start()
{
    var seed = Datetime.Now.Ticks;
    iconSprite.Shuffle(seed);
    priceText.Shuffle(seed); // use the exact same seed again to produce the same random sequence
}

相关问题