0

I have an array of Employee's called m_AllEmployees. Employee inherits from Unity's ScriptableObject class allowing me to create an asset in Unity. However, when I set the value of a field in employee it changes the value of the item in the array and therefore the asset in Unity. I need it to be copied so that they are separate and independent Employees.

Employee employee = m_AllEmployees[index];

mr-matt
  • 218
  • 1
  • 8
  • 20
  • You need DeepCopy/Clone. One way is to implement ICloneable then make DeepCopy (assign all propertoies from one to another) in Clone method. Other (hac) way will be to Serialize the object then Deserialize. you will get 2 separate instances. – Prateek Shrivastava Nov 19 '18 at 03:30
  • Possible duplicate of [How do you do a deep copy of an object in .NET (C# specifically)?](https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-of-an-object-in-net-c-specifically) – mjwills Nov 19 '18 at 03:30
  • 1
    Create a new `Employee` instance and assign all the properties from the other employee which you want to copy. – CodingYoshi Nov 19 '18 at 03:32
  • I can't serialize it because Unity's `ScriptableObject` is not serializable. – mr-matt Nov 19 '18 at 03:46

2 Answers2

1

Use UnityEngine.Object.Instantiate method for this. It will create a new object out of the object you passed to it and re-serialize all the fields.

Sunius
  • 2,789
  • 18
  • 30
  • Employee isn't a component for a `GameObject`, its a class that inherits `ScriptableObject` so that I can have assets in the project folder. I don't think you can instantiate a `ScriptableObject`. – mr-matt Nov 19 '18 at 04:19
  • You can. ScriptableObject derives from UnityEngine.Object (https://docs.unity3d.com/ScriptReference/ScriptableObject.html) and that's what Instantiate method takes. – Sunius Nov 19 '18 at 04:22
  • Will that create a new asset every time? I don't want to have extra assets or gameObjects. – mr-matt Nov 19 '18 at 04:25
  • No, it will not create a new asset or gameobject. It will create a new instance of ScriptableObject that will be a clone of the original one in memory. – Sunius Nov 19 '18 at 04:28
0

Implement clone/deepCopy method in Employee class and create a new instance by calling it.

Employee employee = m_AllEmployees[index].clone();
tryingToLearn
  • 10,691
  • 12
  • 80
  • 114
  • What do I actually put in the implementation? – mr-matt Nov 19 '18 at 04:16
  • @mr-matt: That depends entirely on what is in that class. For primitive types, string and properly done read-only structs, shallow cloning is enough. But for any reference types deep cloning might be nessesary: https://en.wikipedia.org/wiki/Object_copying#Shallow_copy – Christopher Nov 19 '18 at 04:31