c# - 有没有一种从结构中获取随机值的有效方法?
问题描述
我有一个结构,它具有相同的类型属性:
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();
}
对于此类问题,这可能是一个复杂的解决方案,但如果可能的话,我想知道如何使用结构来做到这一点。
解决方案
我有固定数量的“类型”,更准确地说,是在 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;
推荐阅读
- r - 仅从光栅中的 Tif 文件中读取特定范围的坐标 - R
- java - java如何在计算后通过舍入将int保持为int
- python-3.x - 函数不会打印任何东西
- c++ - 如何在不强制降级的情况下设置最低 C++ 标准?
- python - 检查给定列表是否是较大列表的子列表
- parse-platform - Parse 的 afterSave 处理程序中的“返回”有什么意义
- python - “ValueError:输入 0 与层 gru1 不兼容:预期 ndim=3,发现 ndim=4”
- reactjs - SlateJS - 悬停工具栏示例问题 - 选择和工具栏随机消失
- c# - 注册用户时防止覆盖 SaveChagesAsync()
- python - 在python中裁剪图像上的字母的最佳方法