Unity3D中的随机数? [英] Random Numbers in Unity3D?

查看:1120
本文介绍了Unity3D中的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现的是如何创建随机数.伟大的.但是,该解决方案在其他功能中不起作用.为了创建一个随机数,我使用了

What I found was how to create random numbers. Great. This solution, however, was not working in other functions. To create a random number, I used

Random randomDirection = new Random();
int directionChoice = randomDirection.Next(1, 4); 

在一个名为敌人敌人(){};的函数中

inside of a function called enemyWalk(){};

但是,这导致了错误:

类型"UnityEngine.Random"不包含下一步"的定义,并且 找不到类型为"UnityEngine.Random"的扩展方法"Next" (您是否缺少using指令或程序集引用?)

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?)

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

This error does not appear when I take the random integer generator out of the function. Any solutions to fix this problem?

我希望在不做任何事情的情况下使用此代码通过随机选择一个整数来确定自己走的方向(上,左,右或下),然后使用随机双生成器来使敌人徘徊.确定它走的距离.但是,无论何时调用enemyWalk(){};,我都需要生成一个随机数.

I'm hoping to use this code to make my enemy wander around when not doing anything by randomly choosing an integer that decides which direction he walks (up, left, right, or down), then using a random double generator to determine the distance it walks. However I need a random number generated whenever enemyWalk(){}; is called.

推荐答案

在Unity C#中,方法如下

In Unity C# the method is as follows

Random.Range(minVal, maxVal);

请参见 Unity文档-随机

该方法将接受整数或浮点参数.如果使用整数,则返回的随机值的minVal包含,而maxVal排除.在您的情况下,将是:

The method will accept either integer or float arguments. If using ints minVal is inclusive and maxVal is exclusive of the returned random value. In your case it would be:

Random.Range(1,4);

代替Next(1,4).

例如,如果使用浮点数

Random.Range(1.0F, 3.5F);

返回值也是浮点型,在这种情况下,minValmaxVal包含 .

The return value is also a float, minVal and maxVal are inclusive in this case.

这篇关于Unity3D中的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆