Search Unity

Does Unity has a common interface for generic type casting?

Discussion in 'Scripting' started by opeca, Mar 12, 2014.

  1. opeca

    opeca

    Joined:
    Sep 17, 2013
    Posts:
    19
    Hello All,

    I would like to ask, that is there any interface or other way to solve for Unity to achieve generic type casting successfully?

    I got failed casting for it ( Cannot convert type 'UnityEngine.Object' to 'T' ):

    Code (csharp):
    1.         public T LoadExternal(string objectName)
    2.         {
    3.             Object instance = Instantiate((Resources.Load(objectName, typeof(T))));
    4.  
    5.             return (T)instance;
    6.         }
    Thank you!
     
  2. TheRealBanbury

    TheRealBanbury

    Joined:
    Dec 15, 2013
    Posts:
    248
  3. Gibbonator

    Gibbonator

    Joined:
    Jul 27, 2012
    Posts:
    204
    Do you need to add a constraint?
    Code (csharp):
    1.  
    2. class YourClass<T> where T : UnityEngine.Object // <-- Constraint
    3. {
    4.   ...
    5.  
    6.   public T LoadExternal(string objectName)
    7.   {
    8.     Object instance = Instantiate((Resources.Load(objectName, typeof(T))));
    9.     return (T)instance;
    10.   }
    11. }
    12.  
     
  4. opeca

    opeca

    Joined:
    Sep 17, 2013
    Posts:
    19
    Thank you, that's what I'm looking for!
     
  5. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    You need to add <T> to your method declaration:

    Code (csharp):
    1.  
    2. public T LoadExternal<T>(string objectName)
    3. {
    4.     Object instance = Instantiate((Resources.Load(objectName, typeof(T))));
    5.     return (T)instance;
    6. }