StartCoroutine in a public static void

Hi,

I’m writing a script for on-screen notifications that I want to call with a simple command from any other script using: “OnScreenNotification.ShowPopup (“Notification text.”);”

This is my first time working with anything static and I’m kind of having trouble getting the hang of it.
What I’m trying to do is start a coroutine whenever a script calls for OnScreenNotification.ShowPopup. The popup would then show up for a few seconds and then disappear again.

Sadly, I keep getting an error for StartCoroutine (“ShowOSN”);

error CS0120: An object reference is required to access non-static member `UnityEngine.MonoBehaviour.StartCoroutine(System.Collections.IEnumerator)’

It does change the UI text, but the coroutine doesn’t start.
I’ve read a bunch of other questions from people about this problem, but so far none of them seemed to fix my problem.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class OnScreenNotification : MonoBehaviour {

	public static OnScreenNotification instance;

	public Image OSNBg;
	public Animator OSNAnim;
	public Text OSNText;

	public static bool canDisplay;

	public static void ShowPopup(string notificationtext) {
		GameObject.Find ("OSNText").GetComponent<Text> ().text = notificationtext;
		OnScreenNotification.canDisplay = true;
		StartCoroutine ("ShowOSN");
	}

	void Start () {
		OSNBg = GameObject.Find ("OnScreenNotification").GetComponent<Image> ();
		OSNAnim = GameObject.Find ("OnScreenNotification").GetComponent<Animator> ();
		OSNText = GameObject.Find ("OSNText").GetComponent<Text> ();
	}
	
	private IEnumerator ShowOSN () {
		OSNBg.enabled = true;
		OSNAnim.enabled = true;
		OSNText.enabled = true;
		yield return new WaitForSeconds (5);
		OSNBg.enabled = false;
		OSNAnim.enabled = false;
		OSNText.enabled = false;
	}
}

StartCoroutine is an instance method of MonoBehaviour. So you need an instance of any component to actually call StartCoroutine. So there’s no way to use it directly inside a static method since a static method isn’t bound to any instance.

Since that class seems to be some sort of singleton (because of your static “instance” variable) you can use this variable to start the coroutine. Furthermore you should avoid calling StartCoroutine with a string.

In your code it doesn’t look like you initialize your “instance” variable anywhere. You have to initialize it inside Awake.

void Awake()
{
    instance = this;
}

public static void ShowPopup(string notificationtext) {
    instance.OSNText.text = notificationtext;
    canDisplay = true;
    instance.StartCoroutine (instance.ShowOSN());
}