首页 > 解决方案 > 我必须创建随机数骰子

问题描述

我想用如图所示的数字创建一个骰子,{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;
}

标签: c#unity3d

解决方案


首先,如果所有人都注意到第二个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;

推荐阅读