- Home /
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?
Answer by asafsitner · Sep 25, 2011 at 10:56 AM
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
Your answer
Follow this Question
Related Questions
Cant delete clones of prefab 1 Answer
How can i add all the prefabs in the assets directory and sub directories to List or Array ? 0 Answers
How to (in code) save a gameobject that already exists in my scene as a prefab? (c#) 0 Answers
Call a function in an instanciated prefab has no effect on the prefab 2 Answers