Hello, I got this small problem. I am using StartCoroutine for a www request but I can't figure a work-around to access it in a static way. Here is a sample code of what I do:
Just give it a dummy gameobject to run on. Maybe put a script on that gameobject that gives you singleton-style access to it. You should then be able to do something like `dummyComponent.StartCoroutine( whatever );`
using UnityEngine;
/// <summary>
/// Be aware this will not prevent a non singleton constructor
/// such as `T myT = new T();`
/// To prevent that, add `protected T () {}` to your singleton class.
/// </summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
if (applicationIsQuitting) {
Debug.LogWarning("[Singleton] Instance "+ typeof(T) +
" already destroyed on application quit." +
"Won't create again - returning null.");
return null;
}
lock(_lock)
{
if (_instance == null)
{
_instance = (T) FindObjectOfType(typeof(T));
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = "(singleton) "+ typeof(T).ToString();
DontDestroyOnLoad(singleton);
Debug.Log("[Singleton] An instance of " + typeof(T) +
" is needed in the scene, so '" + singleton +
"' was created with DontDestroyOnLoad.");
} else {
Debug.Log("[Singleton] Using instance already created: " +
_instance.gameObject.name);
}
}
return _instance;
}
}
}
private static bool applicationIsQuitting = false;
/// <summary>
/// When unity quits, it destroys objects in a random order.
/// In principle, a Singleton is only destroyed when application quits.
/// If any script calls Instance after it have been destroyed,
/// it will create a buggy ghost object that will stay on the Editor scene
/// even after stopping playing the Application. Really bad!
/// So, this was made to be sure we're not creating that buggy ghost object.
/// </summary>
public void OnDestroy () {
applicationIsQuitting = true;
}
}
If you don’t want a singleton (because your code can become very dependent on them, which makes it difficult to refactor) nor using dummy GameObjects (because you have to create/manage them), you can pass a MonoBehaviour as argument to your static method, and them call StartCoroutine from it.
If you call the static method from a script (Monobehaviour-based object attached to GameObject), you can call the static method using the “this” keyword: