Remove connection between lists or arrays
When i set List1 = List2; I just want to copy elements, problem is, it creates connection whenever i edit List2 it edits List1 immidiately(Don't know how to spell this word).
Please help me how to copy elements or remove connection. Thanks :)
Answer by Statement · Feb 22, 2016 at 08:51 PM
Copying lists: new List(enumerable)
public List<int> list;
public List<int> copyOfList;
void Start()
{
copyOfList = new List<int>(list);
}
Copying arrays: Array.CopyTo
public int[] array;
public int[] copyOfArray;
void Start()
{
copyOfArray = new int[array.Length];
array.CopyTo(copyOfArray, index = 0);
}
Answer by bobor20001 · Feb 22, 2016 at 04:08 PM
I found solution copying every single elements parameters but I hope there is something better than 6 lines of code :)
Variables point to memory addresses containing your data. When you do List1 = List2, you are assigning List1 to point to the same address as List2. There are no 2 arrays with a 'connection' between them; there are 2 variables pointing to the same array.
When you need to get clones of your objects, it feels bothersome that you have to write '6 lines of code', but most of the time you don't want clones. Just make a reusable method that duplicates the object as you need so you only need to write those 6 lines once.
Answer by EmHuynh · Feb 22, 2016 at 08:34 PM
Hello, @bobor20001.
To clone a generic list, do this: List< type > list2 = new List< type >( list1 );
Play with this script in the inspector to see what happens:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ ExecuteInEditMode ]
public class QAScript : MonoBehaviour {
public List< bool > listA1;
public List< bool > listA2;
public List< bool > listA3;
void Start() {
listA1 = new List< bool >() {
false, true, false
};
// Changes made to listA2 will occur to listA1 and vice-versa.
listA2 = listA1;
listA2[ 0 ] = false;
listA2[ 1 ] = false;
listA2[ 2 ] = true;
// Clones listA1. Changes occured to listA3 will not be affect
// the other lists.
listA3 = new List< bool >( listA1 );
}
}
Your answer
Follow this Question
Related Questions
How to declare a list of arrays? 1 Answer
How to create a Matrix / Array / List / Grid of gameObjects? 1 Answer
How to get all children of a Gameobject with a certain component 2 Answers
2D Arrays Help. Why to use 2D arrays for 2 ints 2 Answers
A more optimized way to adjust duplicate integer values In a list? 0 Answers