Home>

I'm making an app with an array in a list.


1) Put three int type arrays into a List
2) The last array entered in Debug is displayed
3) When the button (BacListReturn) is pressed, it is put at the end
The array is deleted and the previous array is displayed in Debug
is.
However, if you actually try it, even if you press the button for some reason
The last 8, 9, 10, 11 will always be displayed.

When you check the number of contents in the list, first press 3 and press the button
It seems to be decreasing one by one.
How can I display 4, 5, 6, 7 when I press the button?

Environment)
PC: mac
Unity2018.3.14f1
Language: C #

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BacListScript: MonoBehaviour
{
    int [] TapNum = new int [4];
    int [] TapNum2 = new int [4];
    int [] TapNum3 = new int [4];
    int [] PasteNum = new int [4];
    List<int []>BacList;
    // Start is called before the first frame update
    void Start ()
    {
        TapNum = new int [4] {0,1,2,3};
        TapNum2 = new int [4] {4,5,6,7};
        TapNum3 = new int [4] {8,9,10,11};
        BacList = new List<int []>();
        BacListAction (TapNum);
        BacListAction (TapNum2);
        BacListAction (TapNum3);
    }
    // Update is called once per frame
    void Update ()
    {
    }
    // Script to add to BacList
    void BacListAction (int [] AddList) {
        for (int i = 0;i<4;i ++) {
            int copyNum = AddList [i];
            PasteNum [i] = copyNum;
        }
        BacList.Add (PasteNum);
    }
    // Delete one element from BacList and return
    public void BacListReturn () {
        BacList.RemoveAt (BacList.Count -1);
        for (int j = 0;j<4;j ++) {
             Debug.Log ("baclist" + j + ":" + BacList [BacList.Count -1] [j]);
        }
    }
    public void CheckList () {
        Debug.Log ("baclistCount" + BacList.Count);
    }
}
  • Answer # 1

      

    BacList.Add (PasteNum);

    PasteNum added to BacList in this line isreference typefor int [].
    Therefore, what is added is a reference to PasteNum, so there is only one entity no matter how many times it is added.

      

    PasteNum [i] = copyNum;

    Because the contents of PaseNum are rewritten in this line, BacList [0], [1], [2] referring to it seems to have been rewritten in the same way.
    This means that all the BacList elements are 8,9,10,11 added last.

    As a countermeasure,
    I think PasteNum should be a local variable inside BacListAction.