Unity3D_(API)Random随机数

 

 

  Unity随机数Random官方文档:  传送门

 

  一、生成一个随机数

  二、Random.InitState()生成伪随机数

  三、官方文档中常用的方法

 

  创建一个Cube用来挂载Random_Gary.cs脚本

  整数类型:Random.Range(min,max):  返回一个随机整数,在min(包含)和max(不包含)之间

  小数类型:Random.Range(minf,maxf)时,返回一个随机浮点数,在minf(包含)和maxf(包含)之间。此时包括临界值

 

一、生成一个随机数

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Random_Gary : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        print(Random.Range(4,10));
    }
}
Random_Gary.cs

 

  

二、Random.InitState(0)生成伪随机数

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Random_Gary : MonoBehaviour {

    // Use this for initialization
    void Start () {
        //设定一个种子
        Random.InitState(0);
    }
    
    // Update is called once per frame
    void Update () {
       if(Input.GetKeyDown(KeyCode.Space))
        {
            print(Random.Range(4,100));
        }
    }
}
Random_Gary.cs

 

  可以看出,场景中第一次生成了26、26、68、42、13,第二次重新加载场景时,依然是这几个数,这就和在Start()函数中设置的随机种子有关了

  要设置随机种子可用  System.DateTime.Now.Ticks

  DataTime.Now.Ticks 的值表示自 0001 年 1 月 1 日午夜 12:00:00 以来所经历的以 100 纳秒为间隔的间隔数,可用于较精确的计时

  返回的是一个long类型,强转为int类型

 

    //设定一个种子
        Random.InitState(0);
        //设置一个随机种子
        Random.InitState((int)System.DateTime.Now.Ticks);

 

 

三、官方文档中常用的方法

  Random.value:可随机生成三种颜色  传送门

  Random.state:可保存生成随机序列的状态  传送门

  Random.rotation:可随机得到游戏物体一个朝向得到一个四元数  传送门

  Random.insideUnitCircle:可避免在同一个位置生成两个敌人  传送门

 

posted @ 2018-11-11 10:40  Cynical丶Gary  阅读(21590)  评论(0编辑  收藏  举报