How to read variables from a script which is attached to an instanced GameObject?

I’m trying to use PlayerBehaviour player = GetComponent< PlayerBehaviour >(); but I get this error “NullReferenceException: Object reference not set to an instance of an object”

What I’m I doing wrong?

edit : the gameObject is not in the scene when the game start… I spawn it with Instantiate(Resources.Load(“Lumbermill”), gameObject.transform.position, Quaternion.identity);

edit 2 :

I have 3 scripts (PlotsGUI, ExcavationBehaviour, ExcavationGUI)

In PlotsGUI I use a button to spawn the Game Object “Excavation”

if (GUI.Button(new Rect(30, 180, 200, 20), "Excavation"))
                {
                    Instantiate(Resources.Load("Excavation"), gameObject.transform.position, Quaternion.identity);
                    Destroy(gameObject);
                    isToggled = false;
                    print("An Excavation Mine has been created");
                }

ExcavationGUI and ExcavationBehaviour is attached to the Game Object that I have spawned with Instantiate(Resources.Load("Excavation"), gameObject.transform.position, Quaternion.identity);

Now I am trying to access ExcavationBehaviour from another script(PlayerBehaviour) which is attached to another Game Object.

This code(from ExcavationGUI) doesn’t work. It says “NullReferenceException: Object reference not set to an instance of an object”

ExcavationBehaviour excavation = GetComponent<ExcavationBehaviour>();
           
PlayerBehaviour player = GetComponent<PlayerBehaviour>();



   if (GUI.Button(new Rect(30, 180, 125, 20), "Collect"))
                    {
                        player.Stones += excavation.inventory;
                        excavation.inventory -= excavation.inventory;
                        
                    }

The question is completely missing informations about how is your code, how you’re instancing and where are you calling the attached code.

If you’re trying to access the PlayerBehaviour from the same function that instantiates the object then the code is:

// Take care at the spawned position, your code is spawning at the position of the object where is attached this code
GameObject go = (GameObject)Instantiate(Resources.Load("Lumbermill"), gameObject.transform.position, Quaternion.identity);
PlayerBehaviour player = go.GetComponent<PlayerBehaviour>();