首页 > 解决方案 > 有没有一种从结构中获取随机值的有效方法?

问题描述

我有一个结构,它具有相同的类型属性:

public struct SomeTypes
{
    public string type1;
    public string type2;
    public string type3;
    public string type4;
}

它们都被赋予了唯一的价值。我需要做的就是从这个结构中获取一个随机值。

例如:

SomeTypes myTypes;

private string GetRandomType(){
    //Instead of:
    return myTypes.type1; //Or type2 etc.
    //This is what I want:
    return myTypes.takeOneRandom();
}

对于此类问题,这可能是一个复杂的解决方案,但如果可能的话,我想知道如何使用结构来做到这一点。

标签: c#unity3d

解决方案


我有固定数量的“类型”,更准确地说,是在 editor 中分​​配了 Sprites

我会简单地用给定的字段初始化一个数组,并使用它来获取一个随机条目Random.Range

[Serializable]
public struct YourStruct
{
    public Sprite sprite1;
    public Sprite sprite2;
    public Sprite sprite3;
    public Sprite sprite4;

    private Sprite[] sprites;

    public Sprite RandomSprite
    {
        get
        {
            // lazy initialization of array
            if (sprites == null) sprites = new[] { sprite1, sprite2, sprite3, sprite4 };

            // pick random
            return sprites[UnityEngine.Random.Range(0, sprites.Length)];
        }
    }
}

然后像这样使用它

public YourStruct yourStruct;

...

Sprite randomSprite = yourStruct.RandomSprite;

推荐阅读