Search Unity

One list containing gameobjects and strings?

Discussion in 'Scripting' started by zigglr, Jul 9, 2018.

  1. zigglr

    zigglr

    Joined:
    Sep 28, 2015
    Posts:
    82
    Is it possible to make a list containing a mix of gameobjects (specifically sprites) and strings? Something likes this:

    Code (CSharp):
    1. List<string> questions;
    2.  
    3. questions = new list<string>() {
    4. "text 1",
    5. "text 2",
    6. GameObject.Find("sprite1").GetComponent<Image>().sprite,
    7. "text 3",
    8. "text 4"
    9. };
    Thanks
     
  2. FernandoHC

    FernandoHC

    Joined:
    Feb 6, 2018
    Posts:
    338
    yes, you want a dictionary, they are a lost faster than lists, so really recommend them.
    try
    Code (CSharp):
    1. Dictionary <string,Image> myDictionary = new Dictionary <string,Image>()
    2. {
    3. {"text 1",yourImage1},
    4. {"text 2",yourImage2},
    5. {"text 3",yourImage3},
    6. };
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Depending on your use case, you could also do a list of instances of a class. Or even a dictionary with <string, class> can work.
     
  4. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Or, to answer the original question, you could use a list of System.Object (since all classes, including String, derive from that).

    Not that you should do such a thing, most likely. But you could.
     
  5. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Ah, I think I misunderstood the question. I see now he was trying to create a list with a mix of stuff.
    Yeah, there is stuff like arraylist, but as mentioned, they suffer the same issue as you generally don't want to use them due to the need to cast stuff as you don't really know what you are getting out of the list.

    If you give us more info on what you are wanting to do, perhaps we could give you better solutions.
     
  6. zigglr

    zigglr

    Joined:
    Sep 28, 2015
    Posts:
    82
    Thanks. So to get yourImage2, would I use:
    Code (CSharp):
    1. myDictionary[1][1]
    ?
     
  7. Hoshiqua

    Hoshiqua

    Joined:
    Jul 22, 2016
    Posts:
    77
    No, dictionnaries are not two dimensional arrays. Dictionaries rather associate a key to a value, the type of each being defined during the creation of the dictionnary.

    In the example that was given to you, the dictionnary associates string keys with Image values.
    This means that in order to access yourImage1, you'd need to type :
    Code (CSharp):
    1. myDictionnary["text 1"]