Is there a way to clone a prefab at runtime WITHOUT dragging a copy from the project list into a scene?
Yes. The following example shows you, how to do it. You need to place this script in any object from your scene.
Select that object, then you see a PrefabInstatiationExample in the example, where you have ‘Your Prefab’. Drag the prefab that needs to be instantiated there.
Now if you run the scene, that ‘yourPrefab’ will be created on the start.
public class PrefabInstatiationExample : MonoBehaviour {
public GameObject yourPrefab;
public void Start () {
Instantiate (yourPrefab);
}
}
Thanks for the reply. I already knew how to do that.
I guess there really isn’t a way to spawn a prefab without dragging it into the world in some fashion.
Or in JavaScript, should someone ever stumble upon this in the future:
var yourPrefab : GameObject;
function Start(){
Instantiate(yourPrefab);
}
EDIT: What do you mean? All you need to do is assign the variable in the inspector.
You can use Resources.Load, but I’d recommend against that unless you have a specific reason for it. e.g., if you change the name or moves things around, you also have to remember to change the script, and everything in Resources is included in a build regardless of whether it’s referenced, so if you’re not careful you can end up including stuff you’re not using.
–Eric
I forgot all about Resources.Load! Bah, I hate it when I get stuck in one-track mind mode.
So, now my question is this:
How does having 100 prefabs “loaded” on a script, even though you don’t use them all, affect performance? The prefab would contain a mesh and several scripts. I can test this myself; I’m just curious of others results ![]()