Problem with List

Hello,

When im in my game I can go to a menu, which is another scene. When I come back from this menu and load the game again I have the problem that the following list will be ruined:

public static var playerRows = new List.<GameObject>();

The Count of the list will still be the same, but the gameObjects inside the list will be gone and set to null.

Now my solution to this problem was to check if one of the gameobjects in the array is null, and if this is null it means that all the other gameobjects are null too, because the player went to another scene.
So when it is null I will fill all the positions in the array with the corresponding gameobjects again.

if(playerRows[0].gameObject == null)
	{
		playerRows.Add(checkWinRow1);
		playerRows.Add(checkWinRow2);
		playerRows.Add(checkWinRow3);
		playerRows.Add(checkWinRow4);
		playerRows.Add(checkWinRow5);
		playerRows.Add(checkWinRow6);
		playerRows.Add(checkWinRow7);
		playerRows.Add(checkWinRow8);
		playerRows.Add(checkWinRow9);
		playerRows.Add(checkWinRow10);
		playerRows.Add(checkWinRow11);
		playerRows.Add(checkWinRow12);
	}

This works perfectly! But, I get the following error:

Now I dont know what todo, cause the solution I made works perfectly, but having alot of errors in my console doesnt really give me the feeling I did a good job…

Is there a way I can fix this, or how can I do this in another way?

PlayerRows is probably empty. So you cant get playerRows[0]. Check if player rows.Count is > 0 before you try to get the first element.

To make the system “safer” from those kinds of errors, you could simply re-initialize everything as soon as you load a new level. Clear the list, and add the items to it again. This way, you don’t have to care if the objects got nulled out, because you are actively taking care of it yourself.

Thanks for the information!!
I fixed it by always nulling the object at function Start() and then reassigning the GameObject List value to it.

public static var playerRows = new List.<GameObject>();

function Start()
{
	playerRows = null;
	playerRows = new List.<GameObject>();
	playerRows.Add(checkWinRow1);
	playerRows.Add(checkWinRow2);
	playerRows.Add(checkWinRow3);
	playerRows.Add(checkWinRow4);
	playerRows.Add(checkWinRow5);
	playerRows.Add(checkWinRow6);
	playerRows.Add(checkWinRow7);
	playerRows.Add(checkWinRow8);
	playerRows.Add(checkWinRow9);
	playerRows.Add(checkWinRow10);
	playerRows.Add(checkWinRow11);
	playerRows.Add(checkWinRow12);
}

As you see I also assign the list before any function is running, because otherwise unity will give me “is not member of” errors. But then I redo everything when the Start function is running.

Better move this to Awake.
Static variables are not serialized between game sessions. So, whenever the scene starts

public static var playerRows = new List.<GameObject>();

is executed, so you get error that argument is out of range.