Unity3D中的随机数?

Jef*_*eff 6 c# random artificial-intelligence unity-game-engine

我发现的是如何创建随机数.大.但是,该解决方案不适用于其他功能.为了创建随机数,我使用了

Random randomDirection = new Random();
int directionChoice = randomDirection.Next(1, 4); 
Run Code Online (Sandbox Code Playgroud)

在一个名为enemyWalk(){}的函数内部;

但是,这导致了一个错误:

类型'UnityEngine.Random'不包含'Next'的定义,也没有找到'UnityEngine.Random'类型的扩展方法'Next'(你是否缺少using指令或汇编引用?)

当我从函数中取出随机整数生成器时,不会出现此错误.解决这个问题的任何解决方案?

我希望通过随机选择一个决定他行走方向(向上,向左,向右或向下)的整数,然后使用随机双生成器确定距离,使用此代码让我的敌人在不做任何事情时四处闲逛它走了.但是我需要在enemyWalk(){};调用时生成一个随机数.

小智 12

如果您使用的是Unity,则快速搜索表明该方法如下:

Random.Range(minVal, maxVal);
Run Code Online (Sandbox Code Playgroud)

请参阅此处Unity文档 - 随机

请记住,minVal包容性的,并maxVal独家使用整数方法重载时,返回的随机值.在你的情况下,它将是:

Random.Range(1,4);
Run Code Online (Sandbox Code Playgroud)

而不是Next(1,4).

如果使用浮动按照:

Random.Range(1.0F, 3.5F);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,minVal和maxVal都包括在内.

我希望这有帮助.


Bra*_*NET 6

简单的解决方案就是使用.NET的Random类,它恰好位于System命名空间中:

using System;

...

//Or System.Random without the using
Random randomDirection = new Random();
int directionChoice = randomDirection.Next(1, 5);
Run Code Online (Sandbox Code Playgroud)

如果您想使用Unity,请致电Range而不是Next:

int directionChoice = randomDirection.Range(1, 5);
Run Code Online (Sandbox Code Playgroud)

请注意,"max" 在两种情况下都是独占的,因此您应该使用5来返回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
Run Code Online (Sandbox Code Playgroud)