[Unity] 引用类型 深度复制

7 篇文章 0 订阅

本人开发过程中碰到过的情况,需要创建一个引用类型(GameData)变量的临时变量(TempData)。

但是众所周知如果直接永等于号赋值(GameData= TempData),那么无疑它们两个都将指向同一地址,改变其中任何一个,两个都将一起改变于是采用深度复制的方法


 首先该类要序列化

[System.Serializable]
public class GameData
{
    public bool IsNewGame;
    public float MusicValue;
    public float SoundValue;

    public Resolution[] Resolutions;
    public int ResolutionIndex;
    public bool IsFullScreen;
    public bool IsDebug;


    //默认值
    public GameData()
    {
        ResolutionIndex = 0;
        IsNewGame = false;
        MusicValue = 0.5f;
        SoundValue = 0.5f;
        IsFullScreen = false;
        IsDebug = true;
        Resolutions = new Resolution[] {
            new Resolution(1920,1080),
            new Resolution(1080,720),
            new Resolution(2580,1080),
        };
    }
}

然后写一个复制使用类

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

public class Clone  {

    public static T DeepCopy<T>(T source) {

        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", "source");
        }
        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }
        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}

使用 

这样data和temp指向不同的内存区域

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值