Unity3D 中的随机数?
Random Numbers in Unity3D?
我发现的是如何创建随机数。伟大的。但是,此解决方案不适用于其他功能。为了创建一个随机数,我使用了
Random randomDirection = new Random();
int directionChoice = randomDirection.Next(1, 4);
在名为 enemyWalk() 的函数中{};
然而,这导致了一个错误:
Type 'UnityEngine.Random' does not contain a definition for 'Next' and
no extension method 'Next' of type 'UnityEngine.Random' could be found
(are you missing a using directive or an assembly reference?)
当我从函数中取出随机整数生成器时,没有出现这个错误。有解决此问题的解决方案吗?
我希望使用此代码让我的敌人在什么都不做时四处游荡,方法是随机选择一个整数来决定他走的方向(上、左、右或下),然后使用随机双精度发电机来确定它走的距离。但是,每当调用 enemyWalk(){};
时,我都需要生成一个随机数。
简单的解决方案是只使用 .NET 的 Random
class,它恰好在 System
命名空间中:
using System;
...
//Or System.Random without the using
Random randomDirection = new Random();
int directionChoice = randomDirection.Next(1, 5);
如果你想使用 Unity,请调用 Range
而不是 Next
:
int directionChoice = randomDirection.Range(1, 5);
请注意,"max"在这两种情况下都是独占,因此您应该使用5到return介于1和4之间的值(包括4)
随机获取float
:
Random.NextDouble(); //careful, this is between 0 and 1, you have to scale it
//Also, this one is exclusive on the upper bound (1)
Random.Range(1f, 4f); //max is inclusive now
Unity C#中方法如下
Random.Range(minVal, maxVal);
该方法将接受整数或浮点参数。如果使用整数 minVal
是 inclusive 并且 maxVal
是 exclusive returned 随机值。在你的情况下它将是:
Random.Range(1,4);
而不是 Next(1,4)
。
如果使用浮点数,例如
Random.Range(1.0F, 3.5F);
return值也是一个浮点数,minVal
和maxVal
在这种情况下包含。
我发现的是如何创建随机数。伟大的。但是,此解决方案不适用于其他功能。为了创建一个随机数,我使用了
Random randomDirection = new Random();
int directionChoice = randomDirection.Next(1, 4);
在名为 enemyWalk() 的函数中{};
然而,这导致了一个错误:
Type 'UnityEngine.Random' does not contain a definition for 'Next' and no extension method 'Next' of type 'UnityEngine.Random' could be found (are you missing a using directive or an assembly reference?)
当我从函数中取出随机整数生成器时,没有出现这个错误。有解决此问题的解决方案吗?
我希望使用此代码让我的敌人在什么都不做时四处游荡,方法是随机选择一个整数来决定他走的方向(上、左、右或下),然后使用随机双精度发电机来确定它走的距离。但是,每当调用 enemyWalk(){};
时,我都需要生成一个随机数。
简单的解决方案是只使用 .NET 的 Random
class,它恰好在 System
命名空间中:
using System;
...
//Or System.Random without the using
Random randomDirection = new Random();
int directionChoice = randomDirection.Next(1, 5);
如果你想使用 Unity,请调用 Range
而不是 Next
:
int directionChoice = randomDirection.Range(1, 5);
请注意,"max"在这两种情况下都是独占,因此您应该使用5到return介于1和4之间的值(包括4)
随机获取float
:
Random.NextDouble(); //careful, this is between 0 and 1, you have to scale it
//Also, this one is exclusive on the upper bound (1)
Random.Range(1f, 4f); //max is inclusive now
Unity C#中方法如下
Random.Range(minVal, maxVal);
该方法将接受整数或浮点参数。如果使用整数 minVal
是 inclusive 并且 maxVal
是 exclusive returned 随机值。在你的情况下它将是:
Random.Range(1,4);
而不是 Next(1,4)
。
如果使用浮点数,例如
Random.Range(1.0F, 3.5F);
return值也是一个浮点数,minVal
和maxVal
在这种情况下包含。