Help with looping a coroutine (c#)

Hello,
as you can see, I’m quite new here and I hope you can help me with a little problem.
I’m currently working on an AI script and have now trouble with setting up a coroutine.

An excerpt of the script is here:

private IEnumerator SetGuard() {
		while(true) {
    
			yield return new WaitForSeconds(Random.Range(5, 10));
			SendMessage ("setGuard");
		}
	}

I want that the SendMessage is called every few seconds. The coroutine should start from the beginning, wait some seconds, send the Message and then start again from top, so it loops.
But every time it keeps hanging at the SendMessage function and sends its message every frame. It shall send it only one time and then wait a bit before sending it again. Hope, you get what I mean :wink:

I tried everything I could imagine - allowedly I’m not very familiar with scripting…

It would be great if someone has a few minutes and could help me. Thanks

I assume your problem is because you’re calling the coroutine from Update. Thats why its sending every frame.

Call the co-routine once from your Awake() method. And while(true) is true, it will keep calling SetGuard every 5 seconds.

i.e

    void Awake()
    {
        StartCoroutine("SetGuard");
    }
	
    IEnumerator SetGuard()
    {
        while(true)
        {
            yield return new WaitForSeconds(5);
            Debug.Log("Sending");
        }
    }

There is a second option using InvokeRepeating

So the code will look like this

float startDelay = 0f;
float repeatDelay = 5f;
void Start()
{
 InvokeRepeating("myFunc", startDelay, repeatDelay);
}

void myFunc()
{
Debug.Log("Sending");
}

I just add StartCoroutine(function here());
at the end of the coroutine. this seems to work perfectly