Unity:使用迭代器内部的随机范围结果(掷骰子)



有很多关于如何制作骰子脚本的教程,但由于某种原因,我找不到一个展示如何根据掷骰子发生某些事情的教程。 我知道如何制作随机范围。 但这对于骰子来说太简单了,因为你想让骰子在停止之前看起来它在侧面滚动或旋转。 这似乎意味着我们使用迭代器或IEnumerator或协程,这就是问题所在。 这些不会吐出我们需要的 int 结果(至少在我使用的脚本中没有(。

这是我在教程中使用的骰子脚本。 我还没有找到一种方法可以让骰子结果在 RollTheDice 方法之外的任何地方可见(可用(。

using System.Collections;
using UnityEngine;
public class Dice : MonoBehaviour {
private Sprite[] diceSides;
private SpriteRenderer rend;
private void Start () {
rend = GetComponent<SpriteRenderer>();
diceSides = Resources.LoadAll<Sprite>("DiceSides/");
}
private void OnMouseDown()
{
StartCoroutine("RollTheDice");
}
// Coroutine that rolls the dice
private IEnumerator RollTheDice()
{
int randomDiceSide = 0;
int finalSide = 0;
for (int i = 0; i <= 20; i++)
{
randomDiceSide = Random.Range(0, 5);
rend.sprite = diceSides[randomDiceSide];
yield return new WaitForSeconds(0.05f);
}
finalSide = randomDiceSide + 1;
Debug.Log(finalSide);
}
}

你应该定义一个将 int 作为参数的方法,该方法可以对 int 执行任何你需要做的事情,然后在你屈服之前,在协程中调用该方法,每次滚动的结果。

然后,如果需要,可以在滚动完成后调用另一个方法。

例如:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dice : MonoBehaviour {
private Sprite[] diceSides;
private SpriteRenderer rend;
private List<int> results;
private void Start () {
rend = GetComponent<SpriteRenderer>();
diceSides = Resources.LoadAll<Sprite>("DiceSides/");
}
private void OnMouseDown()
{
StartCoroutine("RollTheDice");
}
private void UseResult(int result)
{
results.Add(result);
}
private void FinishResults()
{
foreach (int i : results)
{
Debug.Log(i);
}
}
// Coroutine that rolls the dice
private IEnumerator RollTheDice()
{
int randomDiceSide = 0;
int finalSide = 0;
for (int i = 0; i <= 20; i++)
{
randomDiceSide = Random.Range(0, 5);
rend.sprite = diceSides[randomDiceSide];
UseResult(randomDiceSide);
yield return new WaitForSeconds(0.05f);
}
FinishResults();
finalSide = randomDiceSide + 1;
Debug.Log(finalSide);
}
}

注意:在电话上输入,请原谅任何语法错误或其他小错误。

是的,IEnumerator RollTheDice(( 显示整个掷骰过程,直到骰子停止。它的最终结果可以在RollTheDice完成时通过rend.sprite访问。

最新更新