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

查看:29
本文介绍了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); 

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

inside of a function called enemyWalk(){};

然而,这导致了一个错误:

However, this caused an error:

类型UnityEngine.Random"不包含Next"的定义和找不到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 文档 - 随机

该方法将接受整数或浮点参数.如果使用 ints minValinclusive 并且 maxVal 是返回的随机值的exclusive.在您的情况下,它将是:

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 在这种情况下是inclusive.

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

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

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