Unity Call function every 0.1 seconds


Unity call function every 0.1 seconds

In Unity call function every 0.1 seconds. This can be done in several ways. I will show two ways of calling a function every 0.1 seconds.

Unity call function every 0.1 seconds using deltaTime

One way is to use the time.deltaTime in the Update() method to call this function every 0.1 seconds.

float elapsedTime;
float timeLimit = 0.1f;

private void Update()
{
    elapsedTime += Time.deltaTime;
    if (elapsedTime >= timeLimit)
    {
        elapsedTime = 0;
        //Rest of your code or function call goes here
    }
}

We just add deltaTime to elapsedTime every time Update() is run. deltaTime is just the time between the frames (as often Update is run). And when elapsedTime is more or equal to 0.1, we reset elapsedTime and we run our code or call a function.

Unity call function every 0.1 seconds using InvokeRepeating

Another way of calling a function repeatedly is to use the InvokeRepeating method. Maybe even easier to use and can easily be triggered from anything that can call a function. Here is a short minimum example for InvokeRepeating.

private void Start()
{
    InvokeRepeating("MyFunction", 0, 0.1f);
}

void MyFunction()
{
    // Run your code here
}

In this example, we start it from the Start method. But as you see it is easy to start it from anywhere. The first parameter in InvokeRepeating is the name of the method to call. Second is when to start repeating this method (in seconds). And third, and last, how often to repeat the method. We wanted it to start right away, so 0 seconds. And repeating every 0.1 seconds.

Interested in making retro type arcade games? Check out my Depth Charge game inspired from a late 70s game.

Have any Question or Comment?

Leave a Reply