Getting all instances of a prefab to move

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!

Everything I see above looks totally legit, at least at first glance, so it’s gonna take a little bit of tracking.

Are there the correct number of dice in your lists?

Are you seeing any errors?

Gotta run it and track down more about what it’s actually doing vs what the code LOOKs like it should do.

To this end, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

That was quick!
There are no errors or warnings.
Yes, I did liberally sprinkle the code with Debug.Logs.
I know that the Update() method is running in the DiceScript, and that the rollDice() method is being executed. I even logged a count of the iterations through the instantiated prefabs!
Because the diceStatic is public, I can see the value changing in the inspector this is changing to false even for the dice that aren’t moving, which is a little suspect and might be a clue.
Only the value of the one dice that actually moves changes it’s value (I did not include the method for evaluating the dice value). I noticed that it’s the last dice (index 4) that is rolling.

Here’s your problem. This cannot be static. :slight_smile:

Yep. That was it!
Thanks!

1 Like