Search Unity

Instantiate using class name

Discussion in 'Scripting' started by pixelthis, Jul 28, 2010.

  1. pixelthis

    pixelthis

    Joined:
    Nov 5, 2008
    Posts:
    120
    So the current practice in Unity is to create a public variable exposed to the editor which references a Prefab from the project panel.

    Instantiate is then used to create a new object of this type.

    Code (csharp):
    1. public Transform myPrefab;
    2. ...
    3. GameObject myObject;
    4. myObject = (GameObject)MonoBehaviour.Instantiate(myPrefab, new Vector3(0,0,0), Quaternion.identity);
    5.  
    I understand that this gives you the ability to change the prefab at any time by dragging a different one to the script.

    However, is there a way to instantiate a new GameObject just using the class name? E.g:

    Code (csharp):
    1. GameObject myObject = new MyPrefab();
    2.  
    Or even something like:

    Code (csharp):
    1.  
    2. GameObject myObject;
    3. myObject = (GameObject)MonoBehaviour.Instantiate(GetType('MyPrefab'), new Vector3(0,0,0), Quaternion.identity);
    4.  
     
  2. Eagle32

    Eagle32

    Joined:
    Jun 20, 2010
    Posts:
    89
    You have to put the prefab you want to be able to instantiate from code in your Resources folder.

    Then you can instantiate in code using

    Code (csharp):
    1. Instantiate(Resources.Load("prefabName"));

    [edit: Resources folder can be anywhere in your Assets folder.]
     
  3. pixelthis

    pixelthis

    Joined:
    Nov 5, 2008
    Posts:
    120
    Thanks. Quick follow-up question - does this externalise the resource, or is it still contained in the final build?
     
  4. Eagle32

    Eagle32

    Joined:
    Jun 20, 2010
    Posts:
    89
  5. pixelthis

    pixelthis

    Joined:
    Nov 5, 2008
    Posts:
    120
    Great tip. Thanks.