Insert a prefab into scene in a script?

I’ve created a prefab called ‘Bullet’ and I’m trying to add it to the scene whenever a player presses space.

I have the following script set up:

void Update () 
{
	if(Input.GetKeyDown(KeyCode.Space))
	{
		GameObject go = new GameObject("Bullet");
	}
}

But when I hit space when the game is running I get an error saying ‘the thing you want to instantiate is null’.

And that’s basically what I probably should expect, but how do I make it a prefab of Bullets?

edit: I’ve found that I can do this by creating a public object variable and manually dragging and dropping the prefab into it from the window pane afterwhich I can simply Initialize from it. but I would rather be able to tell it to load a prefab I know I’ve created, is this possible?

1 Answer

1

That’s not how it works in Unity. You’ll need to use the Instantiate method and a prefab, i.e:

using UnityEngine;
using System.Collections;

public class test : MonoBehaviour 
{
    //drag prefab here in editor
	public Transform InstantiateMe;
	
	// Update is called once per frame
	void Update () 
	{
		if (Input.GetKeyDown(KeyCode.Space))
		{
            //you don't have to instantiate at the transform's positio nand rotation, swap these for what suits your needs
			var go = Instantiate(InstantiateMe, transform.position, transform.rotation);
		}
	}
}

And of course, set whatever properties of the instantiated prefab you want afterwards.
More on Instantiate: http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html

Thanks for this answer, helped me fix my issue lol