I am implementing a deep object copier for Unity.
I found this great serialization/deserialization method here: https://stackoverflow.com/a/78612/3324388
However I hit a snag with MonoBehaviour objects. If the type is a GameObject, I need to use Instantiate instead of the serialization. So I've add a check:
if (typeof(T) == typeof(GameObject))
{
    GameObject clone = Instantiate(source as GameObject);
    T returnClone = clone as T;
    return returnClone;
}
I am able to cast the source as a GameObject (using as) but when I try to do it in reverse it fails with
The type parameter
Tcannot be used with theasparameter because it does not have a class type constraint nor a 'class' constraint.
If I try just casting it like:
if (typeof(T) == typeof(GameObject))
{
    GameObject clone = Instantiate(source as GameObject);
    T returnClone = (T)clone;
    return returnClone;
}
Cannot convert GameObject to type
T
I feel I'm close but I can't quite get the casting right. Do you know what I am missing to get this to work?

 
     
     
    