- Home /
Problems instantiating a prefab (javascript)
Hello, I'm new to using javascript and I am having some trouble.
In my assets folder, I have a prefab named "enemyprefab", and I am trying to make a script so a copy of the prefab will spawn at the location of the object I have attatched the script to. Looking at the Unity manuals on the instantiate command and its discussion of instantiating prefabs, led me to believe that this code:
#pragma strict
var enemyprefab : Transform;
function Start () {
Instantiate(enemyprefab, Vector3 (x, y, 0), Quaternion.identity);
}
function Update () {
}
would give me the result I need, but unfortunately it doesn't work at all. I've looked at other questions on this website about this topic, but I just can't figure out what to do.
Any help is appreciated.
what errors are you getting?
What about the x,y variables? Did you create these variables? Did you assign them?
You have dragged the enemyprefab prefap into the inspector and onto the enemyprefab thing inside this script?
I've tweaked the script a bit so that the x, y, and z, variables are now created and assigned, and I've now put the enemyprefab prefab onto the script with the inspector and there are no longer any errors, but nothing seems to be spawning. The code now looks like:
#pragma strict
var enemyprefab : Transform;
var x: float;
var y: float;
var z: float;
function Start () {
Instantiate(enemyprefab, Vector3 (x, y, z), Quaternion.identity);
}
function Update () {
}
In my experience I never got this to work either. Try this.
#pragma strict
var enemyprefab : Transform;
var clonedObject : Transform;
var x: float;
var y: float;
var z: float;
function Start () {
clonedObject = Instantiate(enemyprefab, Vector3 (x, y, z), Quaternion.identity);
}
function Update () {
}
hey check if it is instantiating in the hierarchy, if it is, it maybe the position is far away from the camera.
Answer by Vonni · May 08, 2013 at 06:02 PM
Why are you using 3 floats and not just Vector3().
In your question you said you wanted it to spawn where the script object is located, use this.
#pragma strict var enemyprefab : Transform; var clonedObject : Transform; var relativePositionOffset : Vector3 = Vector3(0,0,0); function Start () { clonedObject = Instantiate(enemyprefab, transform.position + relativePositionOffset, Quaternion.identity); } function Update () { }
If this doesn't work then I don't know what you are doing wrong. This DOES work.
That works perfectly. That's so much for you help. This is really great.