- Home /
Small Timer in C#?
Because I don't do c# much but anyways I'm trying to do this thing where it will destroy after 2 seconds when it adds time. using UnityEngine; using System.Collections;
public class BossAnimation : MonoBehaviour {
// Use this for initialization
public bool animate = false;
public GameObject boss;
public Camera cam;
public GameObject bubbles;
public double NumberOfSecondsToWait;
private bool IsTiming = false;
private double timer;
void Update ()
{
if(animate)
{
iTween.MoveTo(gameObject, iTween.Hash("path", iTweenPath.GetPath("Boss Path"), "orienttopath", true, "time", 120));
animate = false;
}
if(transform.position.z < -40)
{
boss.transform.position = new Vector3(-95,-18,-40);
Destroy(bubbles.gameObject);
cam.camera.enabled = true;
beginTimer ();
}
if(IsTiming)
{
timer += Time.deltaTime;
}
if (timer > NumberOfSecondsToWait) //This wont call...
{
cam.camera.enabled = false;
Destroy (gameObject);
print ("Time has passed!");
}
}
void beginTimer()
{
timer = 0;
IsTiming = true;
}
}
It all works until I check for the time. I'm sure the answer is pretty simple but I'm not good with c# logic but I have to make this work in c# so my iTween path works. Help would be great!
Answer by sparkzbarca · Apr 22, 2013 at 11:43 PM
time.time is the amount of time in seconds since the game started. Nothing could ever be less than that or at least not
time.time + 2.0 could ever be.
If you want to make a simple timer you need to use time.deltatime
deltatime is the time in seconds between frames (a very small number)
so
void beginTimer()
{
timer = 0;
IsTiming = true;
}
void update(){
if(isTiming)
{
//+= is the same thing as adding to the current variable
//timer = timer + time.delatime is the same thing as time +=... its just faster to use +=
timer += time.deltatime;
}
if (timer > NumberOfSecondsToWait)
{
//do something, like destroy;
}
}
void EndTimer(){
IsTiming = false;
}
thats just for general knowledge
you can already destroy soemthing in a few seconds time
Destroy(gameobject, time in seconds to delay destruction)
so
Destroy(gameobject,5f)
would destroy the game object in 5 seconds.
Still useful to know how to make a timer though.
mark as answered please
i just wanted to make sure, does while loop help in such cases and by help i mean is it more efficient or something like that?
while (isTi$$anonymous$$g) {
timer += Time.deltaTime;
if (timer >= 2.0f) {
isTi$$anonymous$$g = false;
//do whatever thats needed here
break;
}
}
wud this piece of code make sense?
Answer by codecranker · Apr 23, 2013 at 04:31 AM
I see that your class extends from MonoBehavior, in that case you can also use Invoke() and InvokeRepeating(). You can always check their documentation on unity script reference.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
If statement not working correctly. 3 Answers
if function broken? 3 Answers