腳本語言: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按鈕,可以看到打印出來的數據:
參考鏈接:
更為詳細的介紹:http://blog.csdn.net/luyuncsd123/article/details/16919547