-1

I'm currently trying to create a 3D array of objects whose class I call "Blocks". But it seems that every time I create a block instance, one of the values that I pass into the constructor seems to be passing by reference rather than value. So, when I modify the variable -which is a List of enums representing the direction that each face of the block is facing- the lists in each of the block objects changes too. To be clear, I do NOT want to pass by reference, I want each object to have it's own List.

All of my search results are telling me that Unity only passes by value by default so I'm not really sure which questions to start asking and I'm hoping there's just some simple explanation that I'm missing.

Here's a simplified version of the Block class and how I declare the relevant variable.

public class Block
{
    public List<FaceIndex> faceDirections;

    public enum FaceIndex : int
    {
        East = 0,
        West = 1,
        Top = 2,
        Bottom = 3,
        North = 4,
        South = 5,
    }

    public Block(List<FaceIndex> faceDirections)
    {
        this.faceDirections = faceDirections;
    }
}

Here's how I declare the variable in a different class:

public List<Block.FaceIndex> blockFaceDirections;
blockFaceDirections = new List<Block.FaceIndex> { Block.FaceIndex.East, Block.FaceIndex.West, Block.FaceIndex.Top, Block.FaceIndex.Bottom, Block.FaceIndex.North, Block.FaceIndex.South };

Here's how I instantiate it:

new Block(blockFaceDirections);
derHugo
  • 83,094
  • 9
  • 75
  • 115
David Martin
  • 119
  • 9
  • We could (and probably should) mark this question as a duplicate of this then? [How do I clone a generic list in C#?](https://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c) – Max Play Apr 11 '23 at 21:02
  • For reference types (aka classes) the "value" that is passed, is the *reference* – Hans Kesting May 08 '23 at 15:41

1 Answers1

0

As I was typing my question, I decided to rephrase my question in google and found the answer. I'll post this anyways since it was the only answer I could find and it was phrased much differently.

It's this:

List<YourType> newList = new List<YourType>(oldList);

This is where I found the answer: How do I clone a generic list in C#?

David Martin
  • 119
  • 9