- Home /
How to stop a function and start a countdown in a 2D 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 want a countdown to start when all the Gameobject are in the game and no other gameobject to come in the game. Actually the counter restart at 0 and you can put Gameobjects again and again. The idea is, when all the Gameobjects are in the game the countdown starts and after 8 seconds for example it is win. I tried something like if BoxCounter = 0 stop the function but it isn't working very well. Any other ideas?
You can use a coroutine : http://docs.unity3d.com/Documentation/$$anonymous$$anual/Coroutines.html and each loop you may return WaitForSecond http://docs.unity3d.com/Documentation/ScriptReference/WaitForSeconds.html this will give you something like that: (in c#)
IEnumerator Countdown(int time)
{
for(int i = 0 ; i < time ; i++){
// Your custom Draw Counter function.
DrawCounter(time - i);
yield return new WaitForSecond(1);
}
// You can do other things here when the counter reach 0.
CustomRestartFunction();
}
I think after that you could call StartCoroutine(Countdown) in your condition . Read carfully the documentation because I think the javascript code may change
Answer by Rasa · May 23, 2014 at 10:43 AM
void Update()
{
float TimeAfterBoxes = 0.0f;
(GameObject.Find("GameObjectWitGUIText")).guiText.text = "CountDown : " + TimeAfterBoxes; // This will show the Countdown time
if(boxCounter == boxes.length-1)//Based on No. of Boxes You need.
{
TimeAfterColliding += Time.deltaTime;
if( TimeAfterColliding > 8.00f)
{ WIN Concept HERE ; }
}
You can use Time.FixedDeltaTime instead of Time.deltaTime for Speed Update.
Your answer
Follow this Question
Related Questions
Change gravity on button 1 Answer
2D: Rotating to face mouse position with two fixed axes 1 Answer
Basic 2D cannon rotation code not working 1 Answer
Uni2D Play() - Misunderstanding 3 Answers