轻松为游戏生成随机数据。
此静态类提供了几种面向游戏的简单方法来生成伪随机数。
生成器是一个Xorshift 128算法,基于 George Marsaglia 的论文Xorshift RNGs。它使用来自操作系统的具有高熵的种子进行静态初始化,并存储在原生内存中,以便在域重新加载后仍然存在。这意味着生成器在进程启动时仅播种一次,之后完全由脚本控制。
有关种子的更多详细信息,包括如何自行管理种子,请参阅InitState。要了解如何保存和恢复Random的状态,请参阅state。
与 System.Random 对比
此类与 .NET Framework 类System.Random同名,并且具有类似的目的,但在某些关键方面有所不同。
静态与实例化
UnityEngine.Random
是一个静态类,因此其状态是全局共享的。获取随机数很容易,因为不需要new
一个实例并管理其存储。但是,在使用线程或作业时,静态状态会出现问题(如果在主线程之外使用生成器,则会出错),或者如果需要多个独立的随机数生成器时。在这些情况下,管理System.Random
的实例将是更好的选择。
浮点数上限为包含
所有在UnityEngine.Random
中使用或派生自基于浮点数的随机性的属性和方法(例如value或ColorHSV)都将使用包含上限。这意味着,尽管与任何其他给定值一样罕见,但最大值也可能被随机返回。相反,System.Random.NextDouble()
具有排他性最大值,并且永远不会返回最大值,而只会返回略低于它的数字。
性能UnityEngine.Random
中的方法经过测量,其速度比System.Random
中的等效方法快 20% 到 40%。
名称解析歧义
由于类共享名称Random
,因此如果通过using
同时引入了System
和UnityEngine
命名空间,则很容易出现CS0104“不明确引用”编译器错误。要消除歧义,请使用别名using Random = UnityEngine.Random;
,完全限定类型名称,例如UnityEngine.Random.InitState(123);
,或消除using System
,并改为完全限定或使用来自该命名空间的类型的别名。
insideUnitCircle | 返回圆内或圆上的一个随机点,半径为 1.0(只读)。 |
insideUnitSphere | 返回球体内部或球体上的一个随机点,半径为 1.0(只读)。 |
onUnitSphere | 返回球体表面上的一个随机点,半径为 1.0(只读)。 |
rotation | 返回一个随机旋转(只读)。 |
rotationUniform | 返回一个具有均匀分布的随机旋转(只读)。 |
state | 获取或设置随机数生成器的完整内部状态。 |
value | 返回 [0.0..1.0] 内的随机浮点数(范围为包含)(只读)。 |
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.