Board Game only fully works after second time the dice rolls

Hello,
I’m currently making my first game which consists of a simple roll the dice board game like monopoly and when I tryedr to change it from 2 players to a dynamic number of players (i haven’t made the system to add players yet so I’ve been manually adding to an array just to test this first).

The issue i am facing is that when i roll the dice for the first time the player1 doesn’t move, but after that the game works fine has when it comes back to the turn of the 1st player it moves and so on until the game is over.

I’ve been trying to identify this issue with debug.log and trying various tweaks to the code, but i still can’t solve this.

I think the issue is in the coroutine on Dice.cs but has i am not sure i will provide the main two scripts:

Dice.cs:

using System.Collections;
using UnityEngine;

public class Dice : MonoBehaviour
{
    private Sprite[] diceSides;
    private SpriteRenderer rend;
    private int whosTurn = 0;
    private bool coroutineAllowed = true;

    private void Start()
    {
        rend = GetComponent<SpriteRenderer>();
        diceSides = Resources.LoadAll<Sprite>("DiceSides/");
        rend.sprite = diceSides[5];

    }

    private void OnMouseDown()
    {
        if (!GameControl.gameOver && coroutineAllowed)
        {

            GameControl.CheckTurn(whosTurn);
            StartCoroutine(RollTheDice());
        }
    }

    private IEnumerator RollTheDice()
    {
        coroutineAllowed = false;

        int randomDiceSide = 0;

        for (int i = 0; i <= Random.Range(10, 25); i++)
        {
            randomDiceSide = Random.Range(0, 5);
            rend.sprite = diceSides[randomDiceSide];
            yield return new WaitForSeconds(0.05f);
        }

        GameControl.diceSideThrown = randomDiceSide + 1;
        coroutineAllowed = true;

        whosTurn += 1;
        if (whosTurn == GameControl.players.Length)
        {
            whosTurn = 0;
        }

        GameControl.StopMovement(GameControl.players[whosTurn]);
        GameControl.CheckGameOver(GameControl.players[whosTurn]);
    }

}

And GameControl.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Analytics;

public class GameControl : MonoBehaviour
{
    public GameObject[] gameObjects;
    public static Player[] players;
    public static int diceSideThrown = 0;


    public static bool gameOver = false;

    void Start()
    {
        InitializePlayers();
        gameOver = false;
    }

//Initializes players that ahve with unique id, gameobject and it's first waypointindex
    private void InitializePlayers()
    {
        players = new Player[gameObjects.Length];
        int i = 0;
        foreach (GameObject gameObject in gameObjects)
        {
            players[i] = new Player(i, gameObject, 0);
            players[i].gameObject.GetComponent<FollowThePath>().moveAllowed = false;
            i++;
        }
    }

    // Update is called once per frame
    void Update()
    {
        for (int i = 0; i < players.Length; i++)
        {
            if (players[i].gameObject.GetComponent<FollowThePath>().moveAllowed)
            {
                StopMovement(players[i]);
                CheckGameOver(players[i]);
            }
        }


    }

    public static void CheckGameOver(Player player)
    {
        if (player.gameObject.GetComponent<FollowThePath>().waypointIndex == player.gameObject.GetComponent<FollowThePath>().waypoints.Length)
        {
            gameOver = true;
        }

    }
    public static void StopMovement(Player player)
    {
        Debug.Log("move " + (player.startWaypoint + diceSideThrown) + " tiles");// dá 0 no primeiro clique
        Debug.Log("Index" + player.gameObject.GetComponent<FollowThePath>().waypointIndex);
        if (player.gameObject.GetComponent<FollowThePath>().waypointIndex > player.startWaypoint + diceSideThrown)
        {
            player.startWaypoint = player.gameObject.GetComponent<FollowThePath>().waypointIndex - 1;
            player.gameObject.GetComponent<FollowThePath>().moveAllowed = false;

        }

    }


    public static void CheckTurn(int playerToMove)
    {
        Debug.Log("Check turn" +  players[playerToMove].id);
        players[playerToMove].gameObject.GetComponent<FollowThePath>().moveAllowed = true;
    }
}

I hope you guys can help and be patient with me has i’m new to Unity and CSharp :slight_smile:

Here is how to become sure:

If you need more information about what your program is doing as well as how and where it is deviating from your expectations, that means it is…

Time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, 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 names of the GameObjects or Components involved?
  • 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 supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

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

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

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:

https://discussions.unity.com/t/839300/3

If you are looking for how to attach an actual debugger to Unity: https://docs.unity3d.com/2021.1/Documentation/Manual/ManagedCodeDebugging.html

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

If you learn more by debugging and things still seem mysterious…

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
    - links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379

  • Do not TALK about code without posting it.
  • Do NOT post unformatted code.
  • Do NOT retype code. Use copy/paste properly using code tags.
  • Do NOT post screenshots of code.
  • Do NOT post photographs of code.
  • Do NOT attach entire scripts to your post.
  • ONLY post the relevant code, and then refer to it in your discussion.

[Update] I actually had the debug.log at the right place has for the first round it gave 0 (line 60 of Gamecontrol.cs) but after that this variable was correct.

I fixed it but i still don’t know why it worked has this variable on the line 11 of Gamecontrol.cs

 public static int diceSideThrown = 0;

was the problem, because if i put a number bigger than 0 the game starts to work properly.

I tried this to see if the problem was this variable not being initialised at the beginning of the game so I tried to put the value to 3 in hope to see if the first move would be 3 after I rolled the dice for the first time even if the dice rolled other number .
Surprise surprise, the dice rolled 2 and the player moved 2 tiles instead of 3, so I experimented for a bit to see if it was another mistake, but it fixed it!

Although this was the fix It would be awesome if someone could explain why it worked has i’m not understanding why this happened.

Humans are not expected to run code, especially code written like this:

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

Putting lots of code on one line DOES NOT make it any faster. That’s not how compiled code works.

The longer your lines of code are, the harder they will be for you to understand them.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

Again, turn to debugging for this. See above.

NOTE: static means there is one and only one.

Keep in mind that using GetComponent() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.

Here’s the bare minimum of stuff you absolutely MUST keep track of if you insist on using these crazy Ninja methods:

  • what you’re looking for:
    → one particular thing?
    → many things?
  • where it might be located (what GameObject?)
  • where the Get/Find command will look:
    → on one GameObject? Which one? Do you have a reference to it?
    → on every GameObject?
    → on a subset of GameObjects?
  • what criteria must be met for something to be found (enabled, named, etc.)

If you are missing knowledge about even ONE of the things above, your call is likely to FAIL.

This sort of coding is to be avoided at all costs unless you know exactly what you are doing.

Botched attempts at using Get- and Find- are responsible for more crashes than useful code, IMNSHO.

If you run into an issue with any of these calls, start with the documentation to understand why.

There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.

In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.

It is ALWAYS better to go The Unity Way™ and make dedicated public fields and drag in the references you want.

On the topic of simplifying code: if player is a MonoBehaviour then you don’t need to do player.gameObject to access GetComponent. You can just do player.GetComponent.