Edit: As mentioned by sysameca
If your game object is disabled it
won’t run the Start() method at all,
not to mention that GameObject.Find()
can’t find any disabled game objects.
In addition to these points, you cannot start a coroutine from an object that is disabled or destroyed, however, you can still start the coroutine on any other Monobehaviour.
Its recommended that you don’t use any FindObject() by string, as it is pretty slow and costly in the long run, so either store it locally within the inspector, which makes it pretty easy to access and use, or add the script straight onto the object.
Now within the start, you can make it start disabled, while leaving it active within the scene, helps with debugging a bit if that’s the way you do it.
Use this script as a manager/container for your coroutines:
public class MyController : MonoBehaviour
{
}
Use the script here to disable the object
public class MyObject: MonoBehaviour
{
public float sec = 14f;
public MyController MyController;
void Start()
{
MyController.StartCoroutine(LateCall(sec));
}
IEnumerator LateCall(float seconds)
{
if (gameObject.activeInHierarchy)
gameObject.SetActive(false);
yield return new WaitForSeconds(seconds);
gameObject.SetActive(true);
//Do Function here...
}
}
A more advanced implementation would look like this:
public class MyController : MonoBehaviour
{
private static MyController _instance;
private void Awake()
{
if (_instance == null)
_instance = this;
}
public static void DelayedStart(GameObject target, float time, Action onFinishedCallback)
{
_instance.StartCoroutine(DelayedStartCoroutine(target, time, onFinishedCallback));
}
private static IEnumerator DelayedStartCoroutine(GameObject target, float time, Action onFinishedCallback)
{
if (target.activeInHierarchy) target.SetActive(false);
yield return new WaitForSeconds(time);
target.SetActive(true);
onFinishedCallback?.Invoke();
//Do Function here...
}
}
public class MyObject : MonoBehaviour
{
public float sec = 14f;
void Start()
{
MyController.DelayedStart(gameObject, sec, () =>
{
//Do Function Here
});
}
}