- Home /
how to create a counter counting in seconds(for missile lock system)
i'm trying to use a counter to be increased by one (one stands for one second) when the ray is pointing to the enemy object consistently (say for 4 seconds) then we have a missile lock.
iv'e tried to use if statement inside the update, but it increases the counter only once while pointing on the enemy object.
also tried to use while loop inside update _ ,but it is behaving like an infinite loop.
private var lockedTarget : Transform;
var missileLock : boolean = false;
var missileLockTimer : int = 0;
var lockSound : AudioClip;
var missileFire : AudioClip;
private var ray : Ray;
private var hit : RaycastHit;
function Update ()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit) && SpawnRightFlag == true)
{
if(hit.collider.tag.Equals("ptr80") && missileLock == false)
{
audio.PlayOneShot(lockSound);
missileLock = true;
if(hit.collider.tag.Equals("ptr80"))//here tried while instead of if
{
missileLockTimer += 1;
}
if(missileLockTimer >= 4)
{
lockedTarget = hit.collider.transform;
}
}
else if(!hit.collider.tag.Equals("ptr80"))
{
audio.Stop();
missileLock = false;
}
var rPoint: Vector3 = hit.point;
SpawnRight.transform.LookAt(rPoint);
}
}
Please post any relevent code (and format it) so people can help you.
Answer by Ammarov · Feb 09, 2015 at 11:04 AM
thank you guys, yes the solution is by using yield WaitForSeconds (4);
this also helped me: Coroutines_Yield
Answer by Superrodan · Feb 05, 2015 at 11:05 PM
You will likely need to use floats and the time functions in Unity to accomplish this.
Something like this pseudocode solution should probably work. Replace "theTimerShouldBeGoingUp" with whatever condition you want to check and timeVariable with a float you declare to keep track of time.
void Update()
{
if(theTimerShouldBeGoingUp==true)
{
timeVariable += Time.deltaTime;
if(timeVariable>=4.0f)
{
//Missile lock on code goes here
}
}else{
timeVariable=0;
}
}
If you need the time visible as just the seconds counting up, you will want to use this code to cut off the end of the float and display that ins$$anonymous$$d:
int visibleTimer = $$anonymous$$athf.Floor(timeVariable);
Answer by abi-kr01 · Feb 06, 2015 at 05:36 AM
you can also use ienumerator for that say you need to fire a missile after you can lock the enemy make a
boolen targetlocked=true
void update()
{
if(targetlocked)
{
targetlocked =false;
start corutine(firemissle());
}
}
ienumarator firemissle ()
{
//say u need to fire missile after 60 sec
for (int i=0;i<60;i++)
{
yield return new waitforsec(1);
}
fire();
}
//code may be out of syntax as no suggestion from mono develop here :)
Your answer
Follow this Question
Related Questions
Resouce script help 3 Answers
GuiText Score On Mouse Click 1 Answer
Roguelike Elements... 1 Answer
Counter problem 1 Answer
Connecting 2 scripts(javascpt)? 2 Answers