这个想法是你得到 a 和 b 之间的值。如果该值大于或等于先前的值,则增加该值并返回它。其他情况,您按原样返回。
想一想,确实有效。
public int GetUniqueLevelInclusiveOrdinal(int a , int b, int previous){
// given the ordinal numbers from a to b INCLUSIVE,
// so including a and b,
// (*** NOTE, no random int calls in Unity or any system
// work inclusively so take care ***)
// choose one of the numbers from a to b inclusive
// but do not choose "previous"
// which top index to use with Random.Range which is exclusive?
int top = b+1;
// everyday algorithm for excluding one item from a random run
int topExcludeOne = top-1;
int value = Random.Range(a, topExcludeOne);
if (value >= previous) return value+1;
else return value;
}
这是编程中一个非常著名的基本模式......
int result = UnityEngine.Random.Range(0,highest-1);
if (result>=exclude)
return result+1;
else
return result;
在Unity中你必须使用扩展:
public static int RandomIndexButNotThis(this int highest, int exclude)
{
if (highest<2) Debug.Break();
int result = UnityEngine.Random.Range(0,highest-1);
if (result>=exclude)
return result+1;
else
return result;
}
获取 0 到 99 的随机索引
Random.Range(0,100)
获取 0 到 99 之间的随机索引,但不包括 61
100.RandomIndexButNotThis(61)
获取 0 到 9 的随机索引
Random.Range(0,10)
获取 0 到 9 的随机索引,但不包括 8
10.RandomIndexButNotThis(8)
如果是 Unity 新手,扩展介绍 http://answers.unity3d.com/answers/1118868/view.html