Loading new scene, array looses elements after Start() is executed.

I have a setup where I go back and forth between 2 scenes. Entry is at scene 1, then I load scene 2, then I go back to scene 1, this is where the problem occurs.

In one of my classes, that is used in scene 1, I have a GameObject array that I fill with elements in the Start function for the class. For the first time scene 1 is used, everything works fine, but when I come back to the scene the second time, something goes wrong and the array looses it’s elements.

    public class board : MonoBehaviour {
    	// squares is the array we'r looking at
    	private GameObject[] squares;
    
    	// Use this for initialization
    	void Start () {
    		// Using breakpoints, I can confirm that squares is filled up with elements
    		squares = GameObject.FindGameObjectsWithTag ("GameBoardSquare");
    	}
    
    	public Transform GetBrick(int id){
    		Transform t = null;
    		foreach (GameObject go in squares) {
                // This is where the code breaks, element in squares have been nulled
    			if (go.transform.GetComponent<boardSquare> ().ID == id) {
    				t = go.transform;
    			}
    		}
    		//print (5);
    		return t;
    	}
    }

I’ve been looking at the execution order of events and can confirm that SceneManager.LoadScene(“Scene01”) is triggered before the start function in my class. However, the array seems to loose its elements emediaetly after Scene01 is entered and the start function (where I fill up the array) is executed while the game is still in Scene02.

Any pointers, theories or suggested work-arounds are ofc more than welcome. Or ask if there is something I’d need to clarify in the description or code.

Thanks,
.E

Perhaps make the squares array public so you can check to see if it’s filled in the inspector on scene load.

Also, at what point is the GetBrick function called? If it’s called from another Start() function, it could be that it’s being called before this particular Start() is filling it.

You could also try assigning the array in Awake(). It’s called before Start() for script initialization.

Solved,

The problem was not really related to where the code crashed, but related to my EventManager.
In my event manager, I have static functions and events that needed to be cleared out before entering the scene a second time. Otherwise they had function references to an instance of an object that was deleted when scene 1 was un-loaded the first time.