天天看点

unity3d与c#的随机数

前几天,有个前辈让我弄个随机地图,还要求固定随机数字的种子,也就是说,每次不同组件运行的随机数在相同次数下是相同的。

比如

unity3d与c#的随机数

在r1,r2上分别调用随机数的脚本,发现得到的效果在相同位置上是相同的。

之前知道u3d的api有这个固定种子的写法,上网查了下,查到了个这样的写法。。

//c#版本的随机数,固定种子
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class radom : MonoBehaviour {

	// Use this for initialization
	System.Random random;
	void Start () {
		random = new System.Random(1000);
		string str = "";
		Debug.Log ("-------------");
		for (int i = 0; i < 10; i++)
		{
			str += RandomRange(1, 100)+",";
		}
		Debug.Log ("-------------");
		Debug.Log (str);

	}
	
	public int RandomRange(int min, int max)
	{
		return random.Next(min, max);
	}
}
           

当然这个写法也是对的,但是他与u3d的随机函数没关系,因为这个是从system 调用过来的,其实是.NET的东西。

如果大家查u3d的api可以知道,其中并没有random.next的方法,因此这个并不属于u3d特有的东西。。至于u3d的种子应该是这样的

//unity版本的随机数,固定种子
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class radom : MonoBehaviour {

	// Use this for initialization		
	void Start () {		
		Random.InitState (1000);

		string str = "";
		Debug.Log ("-------------");
		for (int i = 0; i < 10; i++)
		{
			str += RandomRange(1, 100)+",";
		}
		Debug.Log ("-------------");
		Debug.Log (str);

	}

	public int RandomRange(int min, int max)
	{
		return Random.Range (min, max);
	}
}
           

因为他是个静态方法,指定种子时候会有所不同。

值得注意的是,我一直是以为他是一个[a,b) 的区间,但是这次查了下发现并不是这样。

如果我们是一个float类型的随机 他其实是[a,b]区间,只有当int时候的随机才是[a,b)区间

Description

Returns a random float number between and 

min

 [inclusive] and 

max

 [inclusive] (Read Only).

Note that 

max

 is inclusive, so using Random.Range( 0.0f, 1.0f ) could return 1.0 as a value.

Description

Returns a random integer number between 

min

 [inclusive] and 

max

 [exclusive] (Read Only).

Note that 

max

 is exclusive, so using Random.Range( 0, 10 ) will return values between 0 and 9. If 

max

 equals 

min

min

 will be returned.