Using InvokeRepeating in the Update method?

I am trying to use the InvokeRepeating function in the Update method so that if a player comes within 4 units of the object it reduces the players health by 1 instantly and then by 1 every 5 seconds. The problem is that InvokeRepeating ignores my repeat rate and just fires constantly. Here is my code:

	void Update () {
        var dist = Vector3.Distance(player.position, transform.position);

        if (dist < 4)
        {
            InvokeRepeating("Damage", .0001f, 5.0f);
        }
	}

And the simple damage class:

    void Damage()
    {
        TakeDamage(1);
    }

I think the problem lies with using the InvokeRepeating() inside of the Update() method, but I’m not sure how it would be fixed. Thanks in advance!!

The update method is for running repeatedly. Using InvokeRepeating in the update method would be like an update within an update method. InvokeRepeating should always be in the Start or Awake methods.

A good solution for this problem is to make your damage a float. Figure out how much damage the player gets per second. Then your code might be:

if (dist < 4)
{
    damage -= perSecondDamage * Time.deltaTime;
}

Or if you still want to call a function you can do:

TakeDamage(perSecondDamage * Time.deltaTime);

If you want a regular interval of damage, a solution is the what I call a timestamp. This code will call TakeDamage() approximately every second. At the top of the file put:

private float timestamp = 0.0f;

Then your code in the Update() loop would be:

if (dist < 4 && Time.time >= timestmap)
{
    TakeDamage(1);
    timestamp = Time.time + 1.0f;
}