- Home /
Newbie... Instantiating a prefab?
Here is my code in my GameMaster script to create an asteroid in my game every second:
var NextAsteroidTimer = 0.0;
var aster : transform;
function Update () {
NextAsteroidTimer += Time.deltaTime;
if (NextAsteroidTimer > 1)
{
NextAsteroidTimer = 0.0;
var asteroid = Instantiate(aster, Vector3(0,0,0), Quaternion.identity);
}
}
But I am not understanding the 'var aster : transform' along with 'aster' being part of the Instantiate statement. Somehow 'aster' has to refer to my prefab which is in my project view as 'prefab_asteroid'. What are the additional step/steps I need to do? I am not getting clarity on what I am reading in the Unity documentation and searching this board and the community board.
Thanks for any help.
Answer by · Aug 20, 2010 at 06:13 AM
Capitalise your 'transform' variable type (updated code below). Then, find the GameObject that this script is attached to, and there will be a field that says "aster" and the value will be "None (Transform)". Drag your prefab_asteroid object onto that field and the link will be complete. Then your game should spawn an asteroid every second.
var aster : Transform; var NextAsteroidTimer : float = 0.0;
function Update () { NextAsteroidTimer += Time.deltaTime; if (NextAsteroidTimer > 1) { NextAsteroidTimer = 0.0; var asteroid = Instantiate(aster, Vector3(0,0,0), Quaternion.identity); } }
ahhh... Thanks! I seem to be missing yet another piece of understading. I have created a prefab for my asteroid in the project menu. I dropped the ".max" asteroid project view object into it. But I can't drop this script into the prefab. I think I am missing understanding this piece as well.
Okay, so if I drop my prefab into the hierarchy view then it all works and my script creates the asteroid object. But dropping the prefab into my heirarchy view creates one instance in the game. If this is the way to do it then how to I stop the prefab drop into hierarchy from creating the first instance of the asteroid?
Select the GameObject that your script is attached to (in the Hierarchy). Find the 'aster' variable in the Inspector (it should show up under the script component). Drag the prefab from the Project onto the aster value (where it says "None (Transform)").
Let me know if you have any troubles.
Your answer
Follow this Question
Related Questions
Instantiate Clones Itself - Rather than Prefab 0 Answers
Can't remove instantiated prefab 0 Answers
Instantiate Prefab 1 Answer
The right way to instantiate a prefab 1 Answer
Associate objects to a prefab 1 Answer