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.

Question Access list in nested class from a different script

Discussion in 'Scripting' started by samvilm, Mar 26, 2023.

  1. samvilm

    samvilm

    Joined:
    Jan 17, 2021
    Posts:
    40
    I have a nested class with a list. I can't seem to access it. What am I doing wrong?! HELP! I've been stuck for ages!

    Code (CSharp):
    1. public class GameControll : MonoBehaviour
    2. {
    3.  
    4. [System.Serializable]
    5. public class ListClas
    6.    {
    7.     private GameObject player;
    8.     public int scoreList;
    9.     public bool playerDead;
    10.     public ListClas(GameObject player, int scoreList, bool playerDead)
    11.     {
    12.         this.player = player;
    13.         this.scoreList = scoreList;
    14.         this.playerDead = playerDead;
    15.     }
    16.    public List<ListClas> playerList = new List<ListClas>();
    17.    }
    18.  
    19. }
    I've tried to access it from a different script like this

    Code (CSharp):
    1.   private GameControll GameController;
    2.     private List<GameControll> playerList;
    3.  
    4.   void OnEnable()
    5.     {
    6.       GameController = FindObjectOfType<GameControll>();
    7.       playerList = GameController.playerList;
    8.        playerList.Add(new GameControll(gameObject, score, playerDead));
    9.        playerList.Add(new GameControll(gameObject, 5, playerDead));
    10.        playerList.Add(new GameControll(gameObject, 6, playerDead));
    11.     }
    But get this error:
    'GameControll' does not contain a definition for 'playerList' and no accessible extension method 'playerList' accepting a first argument of type 'GameControll' could be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    33,456
    In your top snippet, line 16 is within the inner nested class.

    I don't think you intend this.
     
    samvilm likes this.
  3. samvilm

    samvilm

    Joined:
    Jan 17, 2021
    Posts:
    40
    You sir, are a genius.
    Thanks!
     
    Kurt-Dekker likes this.