【问题标题】:Array doesnt give an Out of bounds Error Message while picking a Random item C#/Unity数组在选择随机项 C#/Unity 时不给出越界错误消息
【发布时间】:2020-11-08 20:35:22
【问题描述】:

我有一个初学者问题。为什么这段代码不会产生错误信息?

public Tile[] tiles = new Tile[2];
...
SetTile(0, 0, 0, nocollide, tiles[Random.Range(0,2)]);

数组中有两个项目,但我选择一个从 0 到 2 的值,即三个项目。当我达到 0,1 时,它只会选择第一个项目。但为什么呢?

【问题讨论】:

  • this Random.Range 吗?然后它返回一个浮点数,使其达到 2.0 完全不太可能(但并非不可能)。并且任何 1.9999999999 都将被截断为 1。- 你应该使用一个随机函数来代替你的整数。
  • 因为 Random.Range 方法返回一个在 [0,2) 范围内的数字,这意味着结果可以是 1,0 但不能是 2
  • (哦,没有看到基于 int 的重载;文档的格式很奇怪)

标签: c# arrays unity3d random indexoutofboundsexception


【解决方案1】:
public static int Range(int min, int max);

说明

原因很简单,返回一个介于 min [inclusive] 和 max [exclusive] 之间的随机整数(只读)。

max 是独有的。 Random.Range(0, 10) 可以返回 0 到 9 之间的值。

如果你想包含最大值,那么你可以使用下面的重载方法。

public static float Range(float min, float max);

说明

返回一个介于 min [inclusive] 和 max [inclusive] 之间的随机浮点数(只读)。

最大值是包含。 Random.Range(0.0f, 1.0f) 可以返回 1.0 作为值。

参考:https://docs.unity3d.com/ScriptReference/Random.Range.html

【讨论】:

  • @PeterPeperoni SO 是学习和分享的最佳平台
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 2017-10-20
  • 2013-04-02
  • 1970-01-01
相关资源
最近更新 更多