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

Question I want to select 2 elements in a list and retrieve them for some other behaviour.

Discussion in 'Scripting' started by frankiwinnie, Dec 26, 2022.

  1. frankiwinnie

    frankiwinnie

    Joined:
    Dec 1, 2020
    Posts:
    26
    Code (CSharp):
    1. public class Card: MonoBehaviour
    2. {
    3. bool isPLayed;
    4. }
    5.  
    6.  
    Hello everyone. I have list of cards defined in my code. What I want to do is to retreive a specific number of elements meeting a condition. I could not figure out how to do that. I tried creating another list like below and filling that with a foreach loop however I got Null reference exception error which I think is caused because of the fact that the list was empty at the begining:

    Code (CSharp):
    1. pulic List<Card> cardsPlayed;
    2.  
    3. foreach(Card card in cardDeck)
    4. {
    5. if (card.isPLayed == true)
    6. { cardsPlayed.Add(card) }
    7.  
    8. }
    This does not work. I would be apreciated if someone could enlighten me on this issue. Thanks.
     
  2. chemicalcrux

    chemicalcrux

    Joined:
    Mar 16, 2017
    Posts:
    717
    A NullReferenceException means that you have...a null reference! You need to look at the error to find out exactly what is null.

    Your code contains typos. Please make sure you're copying exactly what you're using. The specifics are very important! Consider these two snippets:

    Code (CSharp):
    1. public class Test : MonoBehaviour {
    2. public List<Card> cardsPlayed;
    3.  
    4. void SomeFunc()
    5. {
    6.   print(cardsPlayed.Count);
    7. }
    8. }
    Code (CSharp):
    1. public class Test : MonoBehaviour {
    2. void SomeFunc()
    3. {
    4.   List<Card> cardsPlayed;
    5.   print(cardsPlayed.Count);
    6. }
    7. }
    The first block will have cardsPlayed initialized as an empty list if Test is attached to a GameObject in the editor (since that's the default for a serialized list), but will spew NullReferenceExceptions if it's attached to something at runtime via AddComponent. The second block will always spew exceptions, since there's no way cardsPlayed is getting initialized.

    It kind of sounds like your code looks like the first block...but I can't say too much more without actually seeing the code! :p
     
    Kurt-Dekker likes this.
  3. frankiwinnie

    frankiwinnie

    Joined:
    Dec 1, 2020
    Posts:
    26
    Thanks for the reply. I will consider your suggestion.