I’m trying to change the side (sprite) of a dice whenever I’m randomizing a new number.
using UnityEngine;
using System.Collections;
public class Dice6 : MonoBehaviour
{
public Sprite[] diceSprites; //An array of 7 sprites, where position 0 is a blank dice
//private SpriteRenderer spriteRenderer; //Unnessesary when I create it in the Start() function
//void Awake()
//{
//diceSprites = Resources.LoadAll<Sprite>("Dice"); //Did not work
//}
void Start()
{
gameObject.AddComponent<SpriteRenderer>(); //Creates a Spriterenderer for the object
gameObject.GetComponent<SpriteRenderer>().sprite = diceSprites[0]; //Sets the blank sprite to the object
}
public int RollDice(int sides)
{
///Roll a die of x number of sides.
int number;
number = Random.Range(1, sides);
UpdateDiceSprite(number);
return number;
}
void UpdateDiceSprite(int nr)
{
switch (nr)
{
case 1:
gameObject.GetComponent<SpriteRenderer>().sprite = diceSprites[1];
break;
case 2:
gameObject.GetComponent<SpriteRenderer>().sprite = diceSprites[2];
break;
case 3:
gameObject.GetComponent<SpriteRenderer>().sprite = diceSprites[3];
break;
case 4:
gameObject.GetComponent<SpriteRenderer>().sprite = diceSprites[4];
break;
case 5:
gameObject.GetComponent<SpriteRenderer>().sprite = diceSprites[5];
break;
case 6:
gameObject.GetComponent<SpriteRenderer>().sprite = diceSprites[6];
break;
default:
break;
}
}
}
The Dice object shows when you start the program. But when you try to roll the dice nothing happens.
After some searching I started wondering if my Object instantiate code is faulty.
public class GameManager : MonoBehaviour {
public Text diceRollText;
public GameObject Dice;
Dice6 d6 = new Dice6();
private int diceRoll = 0;
// Use this for initialization
void Start ()
{
//write Text
diceRollText.text = "Roll the Die by Pressing R.";
Instantiate(Dice, new Vector3(0, 0, 1f), Quaternion.identity);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
//Press R to roll die
diceRoll = d6.RollDice(6);
d6.UpdateDiceSprite(diceRoll);
diceRollText.text = "Dice rolls: " + diceRoll.ToString();
}
...
The object Dice has a prefab of an object with an array of sprites as well as a script called Dice6 which is the top code block.
Thank you for any advice!