I am developing a dice rolling application that can roll multiple dice simultaneously. The app was working well when I wrote it for one dice. I then move the dice GameObject to a prefab, restructured my code accordingly and everything was working well. When I then attempted to create multiple instances of the dice, only one of the dice responds to the diceRoll() method. I feel I’ve done something silly with my references to the script attached to the dice GameObject, but can’t quite work it out.
Please advise what I’m missing so that all dice will roll.
GameController (abbreviated)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
//Dice Instantiation variables
public GameObject dicePrefab;
private List<GameObject> dice = new List<GameObject>();
private List<DiceScript> diceScripts = new List<DiceScript>();
private int numDice = 5;
Vector3 spawnLocation;
bool diceRoll;
bool diceStatic;
Vector3 diceVelocity;
// Start is called before the first frame update
void Start()
{
spawnDice();
}
// Update is called once per frame
void Update()
{
diceRoll = false;
// Detect if spacebar is pressed
if (Input.GetKeyDown(KeyCode.Space))
{
foreach (DiceScript diceScript in diceScripts)
{
diceScript.rollDice(deviceAcceleration, acceleration);
}
}
}
void spawnDice()
{
//Instantiate creates an Object by default. Use "as GameObject"
for (int i = 0; i < numDice; i++)
{
dice.Add(Instantiate(dicePrefab, new Vector3(0, 0, 0), Quaternion.identity));
diceScripts.Add(dice[i].GetComponent<DiceScript>());
}
}
}
DiceScript (abbreviated, attached to the dice Prefab)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DiceScript : MonoBehaviour {
static Rigidbody rb;
public static Vector3 diceVelocity;
public int diceResult;
public bool diceStatic;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody>();
rollDice(false, diceVelocity);
}
// Update is called once per frame
void Update ()
{
diceVelocity = rb.velocity;
// Check when dice has stopped moving
if (diceVelocity.x == 0f && diceVelocity.y == 0f && diceVelocity.z == 0f)
{
evaluateDice();
diceStatic = true;
}
else
{
diceStatic = false;
}
}
public void rollDice(bool deviceAcceleration, Vector3 acceleration)
{
float dirX = Random.Range(-1000, 1000);
float dirY = Random.Range(0, 1000);
float dirZ = Random.Range(-1000, 1000);
rb.AddForce(500 + dirX, 500 + dirY, 500 + dirZ, ForceMode.Force);
rb.AddTorque(dirX, dirY, dirZ);
}
}
Note that on launch, all the dice roll (this is performed within the script in the Start method).
Thanks!