【问题标题】:Deep copy without Serialize没有序列化的深拷贝
【发布时间】:2014-10-10 11:32:03
【问题描述】:

我正在尝试复制同一类的两个不同实例,没有引用,我不知道为什么这很难做到,只需复制就可以了,再见?

顺便说一句,我找到了一个带有 binnaryformatter 的脚本,它可以满足我的要求,但是在我的班级中,我有一个 Texture2D 类型的变量,当我按下播放键时,我有一个错误,说 Texture2D 没有被标记为可序列化。

using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;

public class pichota : MonoBehaviour {

    public List<Pig> johnPigList = new List<Pig>();
    public List<Pig> peterPigList = new List<Pig>();

    void Start () {
        List<Pig> templist = Clone(johnPigList);
        peterPigList = templist;
    }

    public List<Pig> Clone(List<Pig> source)
    {
        BinaryFormatter bf = new BinaryFormatter();
        using (var ms = new MemoryStream())
        {
            bf.Serialize(ms, source);
            ms.Seek(0, 0);
            return (List<Pig>)bf.Deserialize(ms);
        }
    }

    void Update () {
        if (Input.GetKeyDown(KeyCode.G))
        {

            peterPigList[0].number += 2;
        }
    }
}

[System.Serializable]
public class Pig
{
    public int number;
}

还有另一种深拷贝的方法,或者只是序列化纹理 2d 吗?不要笑我,我是这个高级东西的新手

【问题讨论】:

  • 添加更多关于要复制哪个类的信息。是不是来自你自己的代码,成员的范围等等。
  • 为什么不做一个 Pig 构造函数,将 Pig 作为参数并复制构造函数中的成员?
  • 哇鲁道夫,我花了一天一夜试图解决这个问题,这是一个非常简单的解决方案!
  • 拥有一个名为 deepcopy 或 shallowcopy 的函数比克隆或复制构造函数更好,因为它应该是显而易见的
  • @Imapler,您的命名约定在理论上更好,但现实要求您将混合(浅和深)成员副本,因此它从来没有您建议的那么简单。事实上,按照您的命名约定,他最终可能会使用 deepcopy、deepcopy 和 notsodeepcopy 函数来描述他在做什么。

标签: c# generics serialization unity3d binaryformatter


【解决方案1】:

我不知道你为什么需要一堆克隆的纹理。这对我来说似乎很奇怪,我想象诸如程序动画图像之类的东西。

通常,您不能在 Unity 中序列化纹理。 AFAIK 它只是不那样工作。但是您可以使用 Texture2D.EncodeToPNG 将纹理转换为字节数组并对其进行序列化。

无论如何,在编辑器模式下,Unity 允许您使用CopySerialized 克隆不同的对象。此外,还有一些用于复制组件的未记录函数:

UnityEditorInternal.ComponentUtility.CopyComponent(copiedComponent);
UnityEditorInternal.ComponentUtility.PasteComponentAsNew(targetGameObject);

在播放器模式下,如果你想克隆任意对象,那么最好的方法是使用反射而不是序列化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2017-02-05
    相关资源
    最近更新 更多