# 添加随机的游戏元素

## 从数组选择随机项目

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

## 用不同概率选择项目

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

```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;
}```

`if (randomPoint < probs[i])`

...一个小于或等于的测试会避免额外的返回语句，但即便选中一个项目的概率为零，也允许偶尔选中该项目。

## 随机排序

```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;
}
}```

## 从一组项目中非重复选取

```var spawnPoints:Transform[];

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

var numToChoose = numRequired;

for (numLeft = spawnPoints.Length; numLeft > 0; numLeft--) {
// Adding 0.0 is simply to cast the integers to float for the division.
var prob = numToChoose + 0.0 / numLeft + 0.0;

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;`

Page last updated: 2013-06-20