can't access list with GameObjects

in my main.cs code i’m creating a list with players:

public List<GameObject> playerList = new List<GameObject>();

and adding players with:

playerList.Add(player);

I want to update my players list in my canvas so i’m passing the list to my canvas:

myCanvas.GetComponent<CanvasScript>().updatePlayerList(playerList);

and in my CanvasScript i can’t access the gameobjects:

public void updatePlayerList(List<GameObject> playerList)
{
    foreach (GameObject player in playerList)
    {
         Debug.Log("player found: " + player.GetComponent<Player>().playerName);
    }
}

will throw an error.

can you help?

what error

It would help if you could also tell us what specific error you are getting.
Because looking at the code you posted, it should work, and you should be able to access the GameObjects in the List.

The only thing I see wrong in your posted code is that you have a method name that starts with a lower case letter.
Method names should always begin with an upper case letter (as explained in this Microsoft doc), but I do not think that this would be the reason of the error.

NullReferenceException: Object reference not set to an instance of an object
myCanvas.updatePlayerList (System.Collections.Generic.List`1[T] playerList)

playerList.Count gives a size of 1 so i think the GameObject is correctly in the list.

ahhhhh found the solution: my added GameObject is inactive and i’m trying to access a component of it :(:eyes:

thank you for trying to help.

2 Likes

no problem, I’m glad you found the solution :slight_smile: