Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Object.Instantiate in C#

Discussion in 'Scripting' started by mythicwave, Aug 10, 2010.

  1. mythicwave

    mythicwave

    Joined:
    Jul 13, 2008
    Posts:
    144
    I'm using Instantiate to create GameObjects in C#. If I do something like:

    Code (csharp):
    1. GameObject obj = (GameObject) Instantiate(myPrefab, myPt, Quaternion.Identity);
    2.  
    I get a "cannot cast..." error. In Javascript, I can get a GameObject from a call like this without an error. In C# I can however do something like this:

    Code (csharp):
    1. Transform t = (Transform) Instantiate(myPrefab, myPt, Quaternion.Identity);
    2.  
    So how do I get the GameObject out of this call when using C#? I was thinking of using the Object instanceID, but I'm not sure...

    Thanks,

    Brian
     
  2. mythicwave

    mythicwave

    Joined:
    Jul 13, 2008
    Posts:
    144
    Nevermind. I just check Unity Answers and saw I could do something like this:

    Code (csharp):
    1. Transform t = (Transform) Instantiate(myPrefab, myPt, Quaternion.Identity);
    2.  
    3. GameObject obj = t.gameObject;