将GameObject转换回泛型类型<T>

Agg*_*sor 6 c# serialization deep-copy unity-game-engine deserialization

我正在为Unity实现一个深度对象复印机.

我在这里找到了这个很好的序列化/反序列化方法:https://stackoverflow.com/a/78612/3324388

但是我遇到了MonoBehaviour对象.如果类型是GameObject,我需要使用Instantiate而不是序列化.所以我添加了一张支票:

if (typeof(T) == typeof(GameObject))
{
    GameObject clone = Instantiate(source as GameObject);
    T returnClone = clone as T;
    return returnClone;
}
Run Code Online (Sandbox Code Playgroud)

我可以将源代码转换为GameObject(使用as),但是当我尝试反向执行时,它会失败

type参数T不能与as参数一起使用,因为它没有类类型约束,也没有"类"约束.

如果我尝试将它像:

if (typeof(T) == typeof(GameObject))
{
    GameObject clone = Instantiate(source as GameObject);
    T returnClone = (T)clone;
    return returnClone;
}
Run Code Online (Sandbox Code Playgroud)

无法将GameObject转换为类型 T

我觉得我很接近但是我不能完全正确地进行投射.你知道我错过了什么让这个工作吗?

如果我将类型转换为符合,则错误仍然存​​在: 在此输入图像描述

Kay*_*Kay 5

使用as T在return语句,似乎这样的伎俩。在附加到场景中游戏对象的以下测试代码中,我看到的克隆,Test并且控制台为我显示了不同的值Count

public class Test : MonoBehaviour
{
    private static bool _cloned = false;

    public static T Clone<T>(T source) where T : class 
    {
        if (typeof(T) == typeof(GameObject))
        {
            GameObject clone = Instantiate(source as GameObject);
            return clone as T;
        }
        else if (typeof(T) == typeof(PlainType))
        {
            PlainType p = new PlainType();
            // clone code
            return p as T;
        }
        return null;
    }

    public class PlainType
    {
        private static int _counter = 0;
        public int Count = ++_counter;
        public string Text = "Counter = " + _counter;
    }

    public PlainType MyPlainType = new PlainType();

    void Update ()
    {
        if (!_cloned)
        {
            _cloned = true;
            Clone(gameObject);
            PlainType plainClone = Clone(MyPlainType);
            Debug.Log("Org = " + MyPlainType.Count + " Clone = " + plainClone.Count);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)