c# - 我必须创建随机数骰子
问题描述
我想用如图所示的数字创建一个骰子,{1, 2, 3, 4, 8}
但我得到的输出是{2, 3, 4, 5}
. 还要考虑kodiya = dice
。我已将结果映射到各自的精灵。
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began) {
{
Ray touchPosition = Camera.main.ScreenPointToRay(Input.touches[0].position);
RaycastHit hit;
if (Physics.Raycast(touchPosition, out hit))
{
if (hit.collider != null)
{
if (coroutineAllowed)
StartCoroutine("RollKodiya");
}
}
}
}
}
private IEnumerator RollKodiya()
{
coroutineAllowed = false;
int randomKodiya = 1;
for (int i = 0; i <= 20; i++)
{
int[] numbers = { 1, 2, 3, 4, 8 };
int index = Random.Range(0, numbers.Length -1);
randomKodiya = numbers[index];
rend.sprite = kodiya[randomKodiya];
yield return new WaitForSeconds(0.05f);
}
gameControl.kodiyaThrown = randomKodiya + 1;
gameControl.MovePlayer(1);
coroutineAllowed = true;
}
解决方案
首先,如果所有人都注意到第二个int
索引Random.Range
是独占的,那么它应该是
int index = Random.Range(0, numbers.Length);
现在返回 numbers 1, 2, 3, 4, 8
。之前你只能返回值1, 2, 3, 4
,因为你跳过了最后一个。
但是,从您的评论看来,您无论如何都在使用错误的索引!
你说你的列表/数组中有5 个精灵,kodiya
所以唯一允许的索引是0, 1, 2, 3, 4
.
因此,使用 中的随机索引1,2,3,4,8
来访问 的 5 个现有元素是kodiya
没有意义的!
所以你可能宁愿去那里
randomKodiya = numbers[index];
rend.sprite = kodiya[index];
通常,我个人宁愿使用适当的设置数据结构,而不是三个并行的单独数组,例如
[Serializable]
public class DiceResult
{
public int value;
public Sprite sprite;
}
并在您的 Inspector 中配置该单个数组
// Fill in the values and reference the sprite in each element accordingly
public DiceResult[] _diceResults = new _diceResults[5];
然后使用
var index = Random.Range(0, _diceResults.Length);
var result = _diceResults[index];
randomKodiya = result.value;
rend.sprite = result.sprite;
推荐阅读
- python - 我可以将数字转换为 Python 中的字符数吗
- mrtk - PinchSlider 是如何配置的?
- c# - 使用 printDocument 时如何扩展行和列以适合文本
- google-bigquery - 是否有任何特定符号用于为 BigQuery 指定列名?
- opencart - Opencart3中卸载扩展后,用户组有残留
- kubernetes - 如何显示豆荚年龄?
- c# - 升级到 2019.2.13 导致找不到命名空间名称“EventSystems”
- html - Selenium - 如何在 driver.ExecuteScript 字符串中调试代码
- autodesk-forge - 如何在问题创建表单中将角色列表检索到 AssignTo 下拉列表?
- yadcf - yadcf 插件 - 使用 select filter_type 和 custom_func