Convert GameObject back to generic type <T>

I am introducing a universal copier for Unity.

I found this great serialization / deserialization method: stack overflow

However, I fell into the trap of MonoBehaviour objects. If the type is GameObject, I need to use Instantiateinstead of serializing. So I add a check:

if (typeof(T) == typeof(GameObject))
{
    GameObject clone = Instantiate(source as GameObject);
    T returnClone = clone as T;
    return returnClone;
}

I can use the source as a GameObject (using as), but when I try to do it in the reverse order, it does not work with

A parameter Tcannot be used with a parameter asbecause it does not have a class type restriction or a class restriction.

If I try just sketching it like this:

if (typeof(T) == typeof(GameObject))
{
    GameObject clone = Instantiate(source as GameObject);
    T returnClone = (T)clone;
    return returnClone;
}

Cannot convert GameObject to type T

, , . , , ?

, , : enter image description here

+4
2

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);
        }
    }

}
+4

, object:

 public static T Clone<T>(T source)
 {
      if (source is GameObject)
      {
          return (T)(object)Instantiate((GameObject)(object)source);  
      }
      else ...
  }

, , . , , , , , , , , . , .

+4

Source: https://habr.com/ru/post/1691587/


All Articles