Search Unity

  1. Calling all beginners! Join the FPS Beginners Mods Challenge until December 13.
    Dismiss Notice
  2. It's Cyber Week at the Asset Store!
    Dismiss Notice

Problem with list

Discussion in 'Scripting' started by Plana1, May 3, 2018.

  1. Plana1

    Plana1

    Joined:
    Mar 3, 2018
    Posts:
    3
    Hi, ran on this silly problem, if I change list.count of Test1 to 5, when runing game both Test1.count and Test2.count in inspector become 4. This is simple version of code where i ran on this problem.
    Why is not only Test2 chaning count.


    Code (CSharp):
    1.     public List<int> Test1;
    2.     public List<int> Test2;
    3.  
    4.  
    5.     void Start ()
    6.     {
    7.         Test2 = Test1;
    8.          Test2.Remove(Test2[Test2.Count - 1]);
    9.     }
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,175
    Because this is a shallow copy, this means, you copy the reference, you don't duplicate it
    To solve this, do new List<int>(Test1);
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    4,749
    Test2 = Test1. List are reference types. You're not copying the list, you're setting Test2 to point to Test1. They both are the same referenced list.

    @gorbit99 beat me to it. :)
     
  4. Plana1

    Plana1

    Joined:
    Mar 3, 2018
    Posts:
    3
    Just found answer, but thanks and sory for stupid question.