How to use the results of a dice roll?
Lots of tutorials on how to make a dice script. Very few on how to use dice results to do something. I'm wondering how in this script I get the RollTheDice method to "publish" the finalSide result so that I can use it? Or how do I get a method to look inside RollTheDice and find finalSide? I've been stuck on this for days now. Trying different things. I'm too new to programming to really understand.
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);
}
}
Answer by AaronXRDev · Feb 09, 2020 at 04:35 PM
Here's an example that adds a function to call at the end. @rallyall
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);
DiceComplete(finalSide);
yield return null;
}
private void DiceComplete(int dieRoll)
{
//Do whatever you want with the dieRoll here
}
}
I also found this works:
Within the RollTheDice method add:
//name of script using this roll//.diceSideThrown//or whatever you want to call it// = randomDiceSide + 1;
Then in the script that's using it add outside of any method:
public static int diceSideThrown //or the name you gave it// = 0;
Answer by bruhcompany · Feb 09, 2020 at 10:13 AM
try removing randomDiceSide = 0; because you are setting the variable on the coroutine but the coroutine doesn't stop so it sets it to 0 every 0.05 seconds if im wrong im sorry im kinda new to cs
or you can debug.log inside the coroutine but then you gotta stop the coroutine after the log
Your answer
Follow this Question
Related Questions
blending between meshes 1 Answer
Сursor Center of screenand toggle on and off (Unity 5) 0 Answers
uNet: Failed to send internal buffer 0 Answers
Set the username with an inputfield ? 3 Answers
Player Movement - Not moving at all 3 Answers