Search Unity

Editor script - create game object from a prefab

Discussion in 'Scripting' started by Gnimmel, May 1, 2010.

  1. Gnimmel

    Gnimmel

    Joined:
    Apr 21, 2010
    Posts:
    358
    Hello all,

    I'm trying to create a editor script which simply adds a prefab to my scene. I have a bunch of prefabs in a folder called Prefabs, but I can't work out how to put one of those prefabs in the scene. I'll have to add I'm new to unity, but not new to game development in genral. If anyone could point me in the right direction, I'd be very happy.

    Thanks,

    Richard
     
  2. Caliber-Mengsk

    Caliber-Mengsk

    Joined:
    Mar 24, 2010
    Posts:
    689
  3. Gnimmel

    Gnimmel

    Joined:
    Apr 21, 2010
    Posts:
    358
    Thanks for the reply, although thats not the part I'm having trouble with. The part I can't work out is how to get the Transform of the prefab to use in the Instantiate command. I've sort of got a work around for now, using Selection.GetTransforms and selecting the prefabs in the Project window, but I'm sure there is a better way?

    Thanks,

    Richard
     
  4. matthewminer

    matthewminer

    Joined:
    Aug 29, 2005
    Posts:
    331
    I'm unsure if this is what you're looking for, but AssetDatabase.LoadAssetAtPath allows you to access a prefab then instantiate it.

    Code (csharp):
    1. Object prefab = AssetDatabase.LoadAssetAtPath("Assets/something.prefab", typeof(GameObject));
    2. GameObject clone = Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject;
    3. // Modify the clone to your heart's content
    4. clone.transform.position = Vector3.one;
     
  5. Gnimmel

    Gnimmel

    Joined:
    Apr 21, 2010
    Posts:
    358
    Thats what I was looking for. Thanks a lot.

    Richard
     
  6. astracat111

    astracat111

    Joined:
    Sep 21, 2016
    Posts:
    725
    A correction to this code as of 5.6 (I'm not sure how it is in 2017.1 I haven't upgrade just yet)

    You have to put UnityEngine.Object instead of Object above. Hover over .LoadAssetAtPath() in MonoDevelop and you'll see the type it returns.
     
    zagahlo likes this.
  7. ebubeud1996

    ebubeud1996

    Joined:
    Mar 31, 2018
    Posts:
    6


    Thanks.
     
  8. abdalkader4

    abdalkader4

    Joined:
    Oct 23, 2018
    Posts:
    1