Array returns length but no values from another script

I’m sorry if this question seems silly but I just don’t understand how I can get a proper array length and no values returned.

I have two scenes, go_to_scene and startgame.

go_to_scene (all 6 values are returned in the console):

public static string[] playersarray = new string[5]; 
	
	public void PlayBtn() {
		string[ ] playersarray = new string[]{"a", "b", "c", "d", "e", "f"} ;
		
		foreach(string item in playersarray)
        {
            Debug.Log (item);
        }

startgame (null is printed 5 times instead of 6):

 foreach(string item in go_to_scene.playersarray)
{
    Debug.Log (item);
}

In your code, you are creating two different arrays. First, there’s the static playersarray at the top of the class. Then, because you declare the type again, there’s a, second function-scope-only playersarray.


On top of that, your first array has a length of 5, while your second array has a length of 6. Arrays in C# are zero-indexed, so if you want to go from 0-5, then initialize the first one as [6].


Also note it’s easier to read when you use camel-case on variable names, so playersArray is preferable to playersarray (it may also be renamed to e.g. playerNames, if that’s more descriptive of its content, or just players, depending on your preferences).


In sum, do:


public static string[] playersArray = new string[6];

public void PlayBtn()
{
    playersArray = new string[] {"a", "b", "c", "d", "e", "f"};
    
    foreach (string item in playersArray)
    {
        Debug.Log(item);
    }
}

Thank you so much @JPhilipp