- Home /
What is the easiest way to deep copy a list of gameObjects?
How can i make the "A" list have a different memory adress then the "B" one?
List<UnitSegmentScript> A = new List<UnitSegmentScript>();
foreach (GameObject x in B)
{
A.Add(x);
}
Deep copy means that, not only will "A" have a different memory address than "B", but the objects inside A will be distinct clones from the objects inside B. Any changes to objects inside A will not affects any changes to objects inside B. Is this desired behavior?
Also, I assume UnitSegmentScript
is a custom script attached to a GameObject?
Yes that is what i want to happen i want a distinct clone and yes UnitSegmentScript is a custom script attached to a GameObject
you need to clone the gameobjects before simply adding them to the list using Instantiate
foreach (GameObject x in B)
{
GameObject clone = Instantiate(x);
A.Add(clone );
}
Answer by UnityedWeStand · Jul 14, 2020 at 10:12 PM
Ok, if I am understanding your logic, you have:
- A list of GameObjects B
, each with a ScriptData
component attached to them
- A GameObject combatUnit
, which has a UnitSegmentList
component attached to it
- A function in UnitSegmentList
called SetValues()
that takes in one parameter of type List<ScriptData>
You want to send all of the ScriptData
information into the SetValues()
function of the combatUnit
in a way that any modifications to the list data in combatUnit
does not in any way affect the data already stored in B
This is a rather difficult problem, primarily because ScriptData
inherits from MonoBehaviour
, which means that you can't create a copy of an instance of ScriptData
without attaching it to a GameObject, and you would need to create a copy of every GameObject in B
and keep them in scene to achieve your desired results on your current setup.
An easy solution would be to store any information in ScriptData
in a single Dictionary/Array/HashTable, depending on the nature of the data that needs to be passed into combatUnit
. For example, if you had a list of stats:
public class ScriptData : MonoBehaviour
{
public int[] stats;
// whatever else is in the class
}
You could then pass in clones of the stats
variables into list A
List<int[]> A = new List<int[]>();
foreach (GameObject x in B)
{
A.Add(x.GetComponent<ScriptData>().stats.Clone());
}
GameObject combatUnit = Instantiate(unit);
combatUnit.GetComponent<UnitSegmentList>().SetValues(A);
In this way, any changes made to combatUnit
will not be reflected in B
Answer by djmatthy · yesterday
This worked for me:
var returnData = JsonUtility.FromJson<LevelWaveData>(JsonUtility.ToJson(data));
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Copy From Array to List without reference [C#] 2 Answers
Copy of List with scriptableObjects? 0 Answers