Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

can't access list with GameObjects

Discussion in 'Scripting' started by cert, Nov 29, 2019.

  1. cert

    cert

    Joined:
    Feb 10, 2013
    Posts:
    24
    in my main.cs code i'm creating a list with players:

    Code (CSharp):
    1. public List<GameObject> playerList = new List<GameObject>();
    and adding players with:

    Code (CSharp):
    1. playerList.Add(player);
    I want to update my players list in my canvas so i'm passing the list to my canvas:

    Code (CSharp):
    1. myCanvas.GetComponent<CanvasScript>().updatePlayerList(playerList);
    and in my CanvasScript i can't access the gameobjects:

    Code (CSharp):
    1. public void updatePlayerList(List<GameObject> playerList)
    2. {
    3.     foreach (GameObject player in playerList)
    4.     {
    5.          Debug.Log("player found: " + player.GetComponent<Player>().playerName);
    6.     }
    7. }
    will throw an error.

    can you help?
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,745
    what error
     
  3. Team2Studio

    Team2Studio

    Joined:
    Sep 23, 2015
    Posts:
    98
    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.
     
  4. cert

    cert

    Joined:
    Feb 10, 2013
    Posts:
    24
    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.
     
  5. cert

    cert

    Joined:
    Feb 10, 2013
    Posts:
    24
    ahhhhh found the solution: my added GameObject is inactive and i'm trying to access a component of it :(o_O

    thank you for trying to help.
     
    palex-nx and Team2Studio like this.
  6. Team2Studio

    Team2Studio

    Joined:
    Sep 23, 2015
    Posts:
    98
    no problem, I'm glad you found the solution :)