Editor script - create game object from a prefab

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

That’s the command you are looking for.

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

I’m unsure if this is what you’re looking for, but AssetDatabase.LoadAssetAtPath allows you to access a prefab then instantiate it.

Object prefab = AssetDatabase.LoadAssetAtPath("Assets/something.prefab", typeof(GameObject));
GameObject clone = Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject;
// Modify the clone to your heart's content
clone.transform.position = Vector3.one;
9 Likes

Thats what I was looking for. Thanks a lot.

Richard

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.

1 Like

Thanks.

hah