- Home /
How to make a function stop when all the Gameobjects from the array are in the Game?
Hi everybody !
I'm making a little game with 2D objects (box, square, circles, etc...) appearing when I click. I have this code actually making things work : everytime I use the mouseclick a Gameobject is created from the array list in the inspector.
//Changed to an array of objects assign as many as you have in inspector
var boxes : GameObject[];
var boxCounter : int;
function Update()
{
if(Input.GetMouseButtonDown(0))//Checks to see if left mouse button was clicked.
{
CreateBox();
}
}
function CreateBox()
{
var mousePos : Vector2 = Input.mousePosition;
//Depth you want the center of the object to be is z which I used zero
var boxPos : Vector3 = camera.ScreenToWorldPoint(mousePos.x, mousePos.y, 0);
//I used the perfab box's rotation here but you can enter what you'd like as a euler using Quaternion.Euler(x,y,z)
Instantiate(boxes[boxCounter], boxPos, boxes[boxCounter].transform.rotation);
//This will increment if there are more boxes or reset to 0 if it is the last one.
if(boxCounter == boxes.length-1)
{
boxCounter = 0;
}else{
boxCounter ++;
}
}
But now I have a little problem with the last part, the boxCounter. I want another function to start when all the GameObjects in the array are on the game screen. For example, "If boxcounter = number of array {function GamEnding()} else boxcounter ++" ; I don't want the counter to restart at 0 as the last function is working atm. I tried a few things but nothing worked well. Any idea?
Why do you need to reset it to 0 when you have enough boxes ?
Answer by Maerig · May 20, 2014 at 06:38 AM
You can move this part to the Update()
method
if(Input.GetMouseButtonDown(0) && boxCounter == boxes.length-1)
{
CreateBox();
}
or disable the script
if(boxCounter == boxes.length-1)
{
this.enabled = false;
}
or even delete it
if(boxCounter == boxes.length-1)
{
Destroy(this);
}
The first the solution is the safest, while the others are a little faster, but those can be hazardous if you are trying to access this script from another one.