Setting int value in Start() caused error?

Hello.
So today when I got back to my project I got an error that I didn’t have last night, when everything worked fine.

I use a script called SceneDataHolder to hold and give certain data. Among this how many players that are in the scene. This number is used to return a unique number to every player that calls the function.

The problem I got today was that every player got the same number, 0. This was due to SceneDataHolder not increasing the number of players, or resetting it to zero somehow.
I solved the problem but I still haven’t figured out why it happened, or why it worked last night and not today.
Does anyone know why to any of the questions?

Both pre-fixed and post-fixed code down below.
I only have one instance of the script in the scene, I double checked.

Code with the bug. (Pre-fixed)

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

public class SceneDataHolder : MonoBehaviour {

    private static int playersInScene; // This is used to check how many players exist in the scene.

    public static bool playerHasKey = true;

    void Start () {
        playersInScene = 0; // This was the reason why the problem existed.
    }

    public static int GetPlayerID() {
        int giveID = playersInScene;
        playersInScene++;
        return giveID; // This should return 0 for the first player and 1 for the second.
    }
}

Code without the bug. (Post-fixed)

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

public class SceneDataHolder : MonoBehaviour {

    private static int playersInScene = 0; // This solved the problem.

    public static bool playerHasKey = true;
   
    public static int GetPlayerID() {
        int giveID = playersInScene;
        playersInScene++;
        return giveID; // Same as before.
    }
}

It looks like you were probably calling GetPlayerID before the Start function of SceneDataHolder had been run - were you calling GetPlayerID from another Start function? It’s probably best to put the ‘playersInScene = 0’ into an Awake function as that gets called before Start. Alternatively you could put it into a static constructor. For example,

static SceneDataHolder()
{
   playersInScene = 0;
}

Most likely moving the playersInScene = 0; to Awake would have fixed it. This is assuming you only have one SceneDataHolder.

Aaaah! Now it makes sense since I call GetPlayerID in the player controller script in Start().
I didn’t know that Awake gets called before Start so this helped very much.
Thank you both for the advice, I’ll keep it in mind in the future! :slight_smile:

This doc may help you familiarize you with the order: