How can i perform any action after some time interval

Hi Everyone,
Suppose i have a TWO regions A and B, and i want to perform some action when my object will be stay more then 3 seconds in region B. previously my object is in A region.

When i am using Time property then time Counting is start when my scene is load, or if i am writing it in any function then on scene load my Time counting is start.

Like time.deltaTime; So how can i Count time and after reset it to ZERO.

You can either launch a coroutine that checks that your user is still in the region, and after 3 seconds, performs some actions.
If he leaves, it ends the coroutine. (that would be my choice)

IEnumerator doActionIfStayInZone(int zoneID, float timeDelay)
    float elapsedTime = 0;
    while(zoneID == currentZoneID) // with currentZoneID being a global variable
            // do your action here or launch new action coroutine
        elapsedTime = Time.deltaTime;
        yield return null // this means wait 1 frame, you could reduce the number of checks by cheking up every second or 0.5 s with yield return new WaitForSeconds(0.5f)
    yield return null

And you can launch the coroutine a number of ways, through triggers, position detection,… it depends on your scene and your objectives.

or have 3 variables:

  • one indicating the region you are in
  • another setting the “entryTime”.
  • and a third “actionDone” indicating your action was performed

Every time you change zone, the entryTime should be reset to Time.time, and the third variable actionDone reset to false;

currentRegion = "nameOfTheCurrentRegion"; // could also be an object, a IDnumber,...
entryTime = Time.time;
actionDone = false;

Now you can check up on (Time.time - entryTime > 3 sec) and on the region you are in.
if it is the region you want to do something in, the difference is bigger than 3 sec and (actionDone == false), set actionDone to true and perform your action.

if((Time.time - entryTime > 3) && (actionDone == false))
    actionDone = true;
    // Do your action

Hey @vipin, I just actually read your question (thanks to Joyrider :slight_smile: )

the algorithm for this is incredibly simple …

When you enter region B, always call: Invoke( “success”, 3.0 );

When you enter region A, always call: CancelInvoke( “success” );

then write this routine

function success()
    { Debug.Log("you were, in fact, in B for 3 seconds"); }

it’s that simple. Conceptually the fact that you can name the timer makes all the difference (it’s exactly why Unity did this).

Hope it helps. if you are a new user be sure to TICK any answer to close out the question, thanks.