Search Unity

Instantiate and type cast errors

Discussion in 'Scripting' started by tsphillips, Apr 23, 2006.

  1. tsphillips

    tsphillips

    Joined:
    Jan 9, 2006
    Posts:
    359
    Code (csharp):
    1.  
    2. public GameObject myGameObject;
    3.  
    4. ...
    5.  
    6. Object obj = Instantiate(myGameObject);
    7. Object obj2 = obj;
    8.  
    I must be missing something really obvious. Does anyone know why the last line would throw an InvalidCastException? ("Cannot cast from source type to destination type.")
     
  2. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    How sure are you that the exception is thrown in the last line?

    Exceptions in C have line numbers to the the return site not the call site in the stack trace. (In javascript this works correctly.)

    So most likely the cast error happens in the line before. (The line with Instantiate)
     
  3. tsphillips

    tsphillips

    Joined:
    Jan 9, 2006
    Posts:
    359
    I am very sure. :wink:

    After restarting Unity everything worked fine. I have had oddness like this happen before. I would suspect it has something to do with the C# compiler, but I can't reliably repeat it. (The Instantiate() method, in particular, seems to occassionally behave strangely.)
     
  4. wirelessMike

    wirelessMike

    Joined:
    May 20, 2009
    Posts:
    5
    It looks like this still happens, even with the latest version of Unity (2.6). Simply restarting Unity makes the problem go away.
     
  5. Sawakooo

    Sawakooo

    Joined:
    Dec 29, 2015
    Posts:
    1