Search Unity

Question Confusion about making lists equal to each other.

Discussion in 'Scripting' started by Fllufortin, Mar 31, 2023.

  1. Fllufortin

    Fllufortin

    Joined:
    Sep 10, 2020
    Posts:
    1
    Hi, I am new to unity and am trying to make a game. I was wondering how you make two lists have the same elements but not refer to the same place in memory, and how you check whether there values are equal. I know that just saying listOne = listTwo just makes them refer to the same place in memory but am a bit confused about comparing the lists and .Equals. Thank you in advance.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    If you want to create a new list, you must create a new list. List has a constructor which takes any IEnumerable (including another List) and makes a shallow copy:

    Code (CSharp):
    1. List<Whatever> list2 = new List<Whatever>(list1);
     
    Bunny83 likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    As Praetor hints above, broadly there's the notion of a deep and shallow copy, and also this notion:

    Value Types vs Reference Types:

    https://forum.unity.com/threads/hel...a-game-object-with-code.1047332/#post-6779456

    So if you're making a list of a value types, each entry in the list is a distinct instance, whereas with a list of reference types, that might not be the case, depending if you duped the individual target items.