Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How do i loop trough a list but avoid duplicates?

Discussion in 'Scripting' started by BL4CK0UT1906, Nov 27, 2022.

  1. BL4CK0UT1906

    BL4CK0UT1906

    Joined:
    Apr 15, 2022
    Posts:
    26
    Sorry for my english,
    I'm creating an inventory system, i'm strugglin a lot so i'm asking a lot of questions lately. Sorry for that.

    I simply want to instantiate a prefab button as a child of my canvasParent for each iten on my list (inventoryList).
    It's working but i want to avoid duplicates. I won't post whole code because i really think the piece i'll post is self-explanatory.

    inventoryItens = string list of itens.
    canvasParent = ScrollView Content to hold the buttons.

    The problem is,if i get two "keys" it will instantiate two buttons for keys. I simply want to instantiate only one, and then i'll keep registered how many i have.



    void loadItens(){

    inventoryItens.Sort();

    foreach (string itens in inventoryItens){

    GameObject button = Instantiate(buttonPrefab);
    button.name= itens;
    button.GetComponentInChildren<TextMeshProUGUI>().text = itens;
    button.transform.SetParent(canvasParent.transform, false);
    }

    }
     
  2. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    342
    You can use items.Distinct() or any custom "remove duplicates algorithm".
    If you want to track count you can create List or Dictionary and then iterate over items you have doing this kind of logic: if some item type added you increase item count else you add this item.

    Pseudocode:
    Code (CSharp):
    1. public struct ItemData { Type; Count; }
    2.  
    3. var itemData = new List<ItemData>();
    4. foreach (var item in inventoryItems)
    5. {
    6.     if (TryIncreaseExistingItemCount(itemData, item.Type, item.Count))
    7.         continue;
    8.     itemData.Add(new ItemData(item.Type, item.Count);
    9. }
     
    Last edited: Nov 27, 2022
    BL4CK0UT1906 likes this.
  3. BL4CK0UT1906

    BL4CK0UT1906

    Joined:
    Apr 15, 2022
    Posts:
    26
    Thank you so much for the answer. My inventory is pretty simple so i think as of right now "Distinct()" should do the job.
    I'm sorry if i look dumb but how should i use it? Should i check if "itens" is distinct before i instantiate a button?
     
  4. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    342
    Distinct simply removes duplicates. You should do
    foreach (var item in items.Distinct())
    , and if you want to get count you can simply iterate over all non-distinct items and get actual count. It may not be as optimized, but it will work and is ok for something simple.