您的位置:首页 > 移动开发 > Unity3D

Unity 随机数的使用

2014-07-14 16:18 162 查看
  脚本语言:C#

  一个比较常用的例子是游戏中的主角碰到场景中的NPC时,NPC会随机做出反应,例如有50%几率来友好的致敬,25%几率走开,20%几率反身攻击和%%的几率赠送礼物。

创建一个NPCTest脚本,用于模拟NPC动作:

using UnityEngine;
using System.Collections;

public class NPCTest : MonoBehaviour {

//NPC动作几率
float[] probArray = {0.5f , 0.25f , 0.2f , 0.05f};
int probValue;    //NPC选择值

// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {
}

//选择函数,返回NPC的选项下标值
int Choose(float[] probe)
{
float total = 0.0f;
for (int i=0; i < probe.Length; i++) {
total += probe[i];
}

// Random.value方法返回一个0—1的随机数
float randomPoint = Random.value * total;

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

return probe.Length - 1;
}

void OnGUI(){
if( GUI.Button(new Rect(10,70,50,30),"Click") )
{
probValue = Choose(probArray);

switch(probValue){
case 0:
Debug.Log ("NPC向我致敬!");
break;
case 1:
Debug.Log ("NPC离开了!");
break;
case 2:
Debug.Log ("NPC攻击我了!");
break;
case 3:
Debug.Log ("NPC给我钱了!");
break;
default:
Debug.Log("我没有碰到NPC");
break;
}
}
}
}


点击Game视图中的Click按钮,可以看到打印出来的数据:



参考链接:

  更为详细的介绍:/article/2547198.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: