网上看到别人在写这样一个方法,就尝试能够在Unity中使用该方法。

记住要使用的程序包:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public object DeepCopy(object src)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, src);

ms.Seek(0, SeekOrigin.Begin);
object dst = bf.Deserialize(ms);
ms.Close();
return dst;
}

测试代码如下:

int[] temp = new int[] {1,2,3 };

        int[] copy = (int[])DeepCopy(temp);

        copy[1]=34;
        Debug.Log(copy[0]+":"+copy[1]+"--"+temp[0]+":"+temp[1]);

测试结果如下:

1:34--1:2

 

深度拷贝成功,这是使用对象序列化的方法实现的深度拷贝!

相关文章:

  • 2023-04-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-04-28
  • 2021-06-28
  • 2021-07-19
  • 2021-07-17
  • 2021-11-20
相关资源
相似解决方案