Unity 随机数的使用


  脚本语言: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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM