- Home /
How to fix a stuck Coroutine / how to have a coroutine running while another scene is open
I am making a clicker game and whenever I go to a different scene using SceneManager.LoadScene(2); and come back to the other scene the coroutine gets stuck and isn't fixed until it gets updated. Anyone know a way on how to have the coroutine fix itself or know a way to have the coroutine run itself while another scene is open? I have tested and the coroutine doesn't stop with the console but it does in the in game scripts (I have just started using the Scene loading function and I am still getting used to it) Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutoSell : MonoBehaviour
{
public bool SellingOre = true;
public static float CashIncrease = 1;
public float InternalIncrease;
void Update()
{
CashIncrease = GlobalShop.shopPerSec;
InternalIncrease = CashIncrease;
if (SellingOre == false)
{
SellingOre = true;
StartCoroutine(SellTheOre());
}
}
IEnumerator SellTheOre()
{
{
}
if (GlobalOres.OreCount < InternalIncrease)
{
SellingOre = true;
GlobalOres.OreCount = GlobalShop.shopPerSec;
}
else
GlobalCash.CashCount += InternalIncrease;
GlobalOres.OreCount -= GlobalShop.shopPerSec;
yield return new WaitForSeconds(1);
SellingOre = false;
if (GlobalOres.OreCount < GlobalShop.shopPerSec)
{
if (GlobalOres.OreCount >= 1)
{
GlobalCash.CashCount += GlobalOres.OreCount;
GlobalOres.OreCount -= GlobalOres.OreCount;
}
}
}
}
and
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutoOre : MonoBehaviour {
public bool CreatingOre = false;
public static float OreIncrease = 1;
public float InternalIncrease;
void Update () {
OreIncrease = GlobalMiner.MinePerSec;
InternalIncrease = OreIncrease;
if (CreatingOre == false)
{
CreatingOre = true;
StartCoroutine(CreateTheOre());
}
}
IEnumerator CreateTheOre()
{
GlobalOres.OreCount += InternalIncrease;
yield return new WaitForSeconds(1);
CreatingOre = false;
}
}
I tried using Scene$$anonymous$$anager.LoadSceneAsync, but the same thing happens.
You need to make sure that the script persists after the new scene has been loaded, ie it has been "DontDestroyOnLoad" affixed. When loading scene, the drop in frame rate should be expected.
Answer by unity_0sdsWZad6Fwp-A · Jan 19, 2019 at 08:36 PM
Thankyou @haruna9x for the recommendation. I have fixed the issue with some code I had found in a video about serialization. I just made a public static field then put this code under the script.
if (check == null)
{
DontDestroyOnLoad(gameObject);
check = this;
}
else if (check != this)
{
Destroy(gameObject);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612190024im_/https://answers.unity.com/themes/thub/images/avi.jpg)