Version: 2018.1

# 添加随机游戏元素

## 从数组中选择一个随机项

`````` var element = myArray[Random.Range(0, myArray.Length)];
``````

## 选择具有不同概率的项

• 友好问候的几率为 50%
• 逃跑的几率为 25%
• 立即攻击的几率为 20%
• 提供金钱作为礼物的几率为 5%

``````
//JS

function Choose(probs: float[]) {
var total = 0;

for (elem in probs) {
total += elem;
}

var randomPoint = Random.value * total;

for (i = 0; i < probs.Length; i++) {
if (randomPoint < probs[i])
return i;
else
randomPoint -= probs[i];
}

return probs.Length - 1;
}

//C#

float Choose (float[] probs) {

float total = 0;

foreach (float elem in probs) {
total += elem;
}

float randomPoint = Random.value * total;

for (int i= 0; i < probs.Length; i++) {
if (randomPoint < probs[i]) {
return i;
}
else {
randomPoint -= probs[i];
}
}
return probs.Length - 1;
}

``````

`````` if (randomPoint < probs[i])
``````

…更改为“小于或等于”测试将避免额外的 return 语句，但也会允许偶尔选择某个项，即使其概率为零也是如此。

## 加权连续随机值

``````//JS

function CurveWeightedRandom(curve: AnimationCurve) {
return curve.Evaluate(Random.value);
}

//C#

float CurveWeightedRandom(AnimationCurve curve) {
return curve.Evaluate(Random.value);
}
``````

## 列表洗牌

``````//JS

function Shuffle(deck: int[]) {
for (i = 0; i < deck.Length; i++) {
var temp = deck[i];
var randomIndex = Random.Range(0, deck.Length);
deck[i] = deck[randomIndex];
deck[randomIndex] = temp;
}
}

//C#

void Shuffle (int[] deck) {
for (int i = 0; i < deck.Length; i++) {
int temp = deck[i];
int randomIndex = Random.Range(0, deck.Length);
deck[i] = deck[randomIndex];
deck[randomIndex] = temp;
}
}

``````

## 从一组无重复的项中选择

``````
//JS

var spawnPoints: Transform[];

function ChooseSet(numRequired: int) {
var result = new Transform[numRequired];

var numToChoose = numRequired;

for (numLeft = spawnPoints.Length; numLeft > 0; numLeft--) {
// 添加 0.0 只是为了将整数转换为浮点数以进行除法运算。
var prob = (numToChoose + 0.0) / (numLeft + 0.0);

if (Random.value <= prob) {
numToChoose--;
result[numToChoose] = spawnPoints[numLeft - 1];

if (numToChoose == 0)
break;
}
}

return result;
}

//C#

Transform[] spawnPoints;

Transform[] ChooseSet (int numRequired) {
Transform[] result = new Transform[numRequired];

int numToChoose = numRequired;

for (int numLeft = spawnPoints.Length; numLeft > 0; numLeft--) {

float prob = (float)numToChoose/(float)numLeft;

if (Random.value <= prob) {
numToChoose--;
result[numToChoose] = spawnPoints[numLeft - 1];

if (numToChoose == 0) {
break;
}
}
}
return result;
}
``````

## 空间中的随机点

`````` var randVec = Vector3(Random.value, Random.value, Random.value);
``````

`````` var randWithinRadius = Random.insideUnitSphere * radius;
``````

`````` var randWithinCircle = Random.insideUnitCircle * radius;
``````