- Home /
Instantiating Custom Prefabs
I'm having a bloody hell of a time figuring this one out. I'm close, very close. But I can't connect it with prefabs.
A lot of what I have been looking at is in the following document: http://unity3d.com/support/documentation/Manual/Instantiating%20Prefabs.html
However, I can't connect the dots with the prefabs.
In my project I have a sphere prefab that can be picked up when you walk over it. I want to be able to instantiate it at runtime as I am going to be spawning the item in random spots over the map.
var cube : Transform;
function Start () {
for (var y = 0; y < 5; y++) {
for (var x = 0; x < 5; x++) {
var cube = Instantiate(cube, Vector3 (x, y, 0), Quaternion.identity);
}
}
}
From what I understand, I should be able to modify this code to work with my custom prefab that I've named spherePick (this is in the visual interface of Unity).
What am I missing here?
Answer by DaveA · Jun 27, 2012 at 12:22 AM
You have 'var cube' twice. that's confusing it. Set one different, eg: var newcube = Instantiate(cube,
Still doesn't work. not really sure where exactly I need to be referencing the prefab I made; that's really the main thing I'm asking.
I assume you dragged it from the Project list onto the 'cube' field on the Inspector view of your object, correct?
Not exactly sure what you mean here, I have the script attached to a GameObject, yes. Not sure what you mean by cube field.
Well I figured out what you meant and it was exactly the issue I was having.
I needed to change the field in the inspector by dragging my prefab into it.
It works like a dream!
Answer by Chris12345 · Jun 27, 2012 at 01:28 AM
This should work
var cube : Transform;
function Start () {
for (var y = 0; y < 5; y++) {
for (var x = 0; x < 5; x++) {
cube = Instantiate(cube, Vector3 (x, y, 0), Quaternion.identity);
}
}
}
Still, no point in assigning the new clone to the original var. In fact, since he's not using it, no point in assigning it to anything at all.
I feel like I'm getting closer, but it's just not working. Here's what I have (my prefab is called spherePick)
var spherePick : Transform;
function Start () {
for (var y = 0; y < 5; y++) {
for (var x = 0; x < 5; x++) {
Instantiate(spherePick, Vector3 (x, y, 0), Quaternion.identity);
}
}
}