- Home /
Instantiate only one prefab
Ok i have this script:
#pragma strict
var moon : Transform;
private var moonPosition;
var spaceClicks;
var rocketPosX;
var rocketPosY;
var distance = 100;
var spawnMoon = false;
function Start () {
//rocketPosY = rocketPosY + distance;
}
function Update () {
rocketPosX = gameObject.Find("raket").transform.position.x;
rocketPosY = gameObject.Find("raket").transform.position.y + 10;
spaceClicks = gameObject.Find("raket").GetComponent(RocketScript).clicks;
if(spaceClicks == 5)
Instantiate(moon, Vector2(rocketPosX,rocketPosY), Quaternion.identity);
}
In another script, when i press space, a rocket goes up one click. When i press it 5 times a mooon needs to be spawned. With this script i made, it spawns, but it spawns one every frame! How can instantiate only one moon?
Answer by Mehrdad995 · Jul 14, 2015 at 11:16 AM
First of try not to use .Find process as much as possible. you can find it once at start up. in this way you will cache the transform which gonna boost you game.
var rocket : Transform;
function Start()
{
rocket = GameObject.Find("raket").transform;
}
rocketPosX = rocket.position.x;
rocketPosY = rocket.position.y + 10;
and finally you can stop spawning each frame by resetting spaceClicks value to zero after each time it reached 5 So :
if(spaceClicks == 5)
{
spaceClicks = 0;
Instantiate(moon, Vector2(rocketPosX,rocketPosY), Quaternion.identity);
}
I cant really do that since the clicks are the "Score" and cant just be reset.
Then just add a boolean to check if the moon has been spawned :
var moonSpawned = false ;
....
if(spaceClicks == 5 && !moonSpawned)
{
moonSpawned = true ;
Instantiate(moon, Vector2(rocketPosX,rocketPosY), Quaternion.identity);
}
Answer by Simpso · Jul 14, 2015 at 12:28 PM
Cant you add an and to your spaceclicks if statement which checks if teh moon object has already been spawned? If not spawn it else dont.
Answer by zedseven · Jul 14, 2015 at 02:01 PM
You could try checking for weather a moon has been spawned already, and if so, don't do anything.
private GameObject currentMoon;
if(spaceClicks == 5 && currentMoon == null)
{
currentMoon = (GameObject) Instantiate(moon, Vector2(rocketPosX,rocketPosY), Quaternion.identity);
}
Your answer
Follow this Question
Related Questions
How to access a variable from a game object once instantiated (C#) 1 Answer
Any ideas on a simple AI script that doesn't use any drag/drop variables 1 Answer
Instantianig a teleporter prefabs with destination variables 1 Answer
[Solved]Instantiating prefab from a script and destroy it from another one 2 Answers
setting the text of an instantiated prefab's child's guitext object 1 Answer