Interscene coroutine calling

Hello, I’m trying to make something like this:

Scene 1: Main Camera got attached 2 scripts. First script starts coroutine Refresh(), that is placed inside of script 2. This Refresh() should be called every 30 seconds. So lets assume it looks like this:

public IENumerator Refresh() {
   
    Debug.Log("Refreshing.");
    yield return new WaitForSeconds(30);
    StartCoroutine(Refresh());
}

Perfectly working. Now I load Scene 2. There is no longer my main camera that would have Script 2 containing Refresh coroutine and I don’t want to make a new instance of that script. Perfect solution would be to make this Refresh coroutine as static. But if I do so, I can’t use StartCoroutine command inside of it, which is important for constant refreshing.

What I’d like to ask is: Is there any way to start coroutine and make it to be called every 30 seconds even when I load another scene?

Thanks in advance for any help.

First of all recursively calling StartCoroutine is bad. The coroutine should look like this:

public IEnumerator Refresh()
{
    while (true)
    {
        Debug.Log("Refreshing.");
        yield return new WaitForSeconds(30);
    }
}

To solve your actual problem you just have to attach the script to a gameobject that can persist between scenes. You just have to call DontDestroyOnLoad in start:

void Start()
{
    StartCoroutine(Refresh());
    DontDestroyOnLoad(gameObject);
}

This will make this gameobject to stay when you load a new scene and the coroutine will continue to run. Keep in mind that if the script requires references to other objects in the scene, you either have to keep them as well, or you have to reassign the references once the new scene is loaded.