我有一个结构,它具有相同的类型属性:
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 中分配的精灵。
我会简单地用给定的字段初始化一个数组,并使用它来获取随机条目 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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句