InvokeRepeating inside of a class

I am getting the following error:

NullReferenceException: Object reference not set to an instance of an object

var level = new Puzzle();

function Start () {
    // lines above
    this.level.addExplosionEvent(this.explosion1, a, 1000);
    // lines below

So the error is on the line that uses this.level

It happens when I have my Puzzle() class extend MonoBehaviour like this:

public class Puzzle extends MonoBehaviour{


I want to extend MonoBehaviour because inside the class I want to use InvokeRepeating. I have tried to initiate MonoBehaviour instead of extend the class:

var mb = new MonoBehaviour();
mb.InvokeRepeating("explode", 1, 1);

but that doesn’t work. So basically, is there a way to use InvokeRepeating within my class?

I came here while searching why Unity throwing unkown identifier Invoke error.
Error was unclear but your question rang the bell.




var yourObject = new yourObject();


You can’t make the object of the MonoBehaviour with new ().
But to solve your problem you have to send the object of the MonoBehaviour from where you are calling the method. Do check the example below.

Attached is the example which needs to use the StartCoroutine in my case ( InvokeRepeating in your case)

Script in which we need to use InvokeRepeating

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

public class NortificationMessage
	Text textArea;

	public NortificationMessage ()
		textArea = GameObject.Find ("NotificaitonAreaText").GetComponent<Text> ();

	public void DisplayMessage (string messageToDisplay, MonoBehaviour mono)
		textArea.text = messageToDisplay.ToString ();
		mono.StartCoroutine (EmptyTextField());

	IEnumerator EmptyTextField ()
		yield return new WaitForSeconds (5);
		textArea.text = "";

Method from which we need to call the “DisplayMessage

public void DisplayNotification (string messageToDisplay)
			nortificationMessages.DisplayMessage (messageToDisplay, this);

The above method should be present in the class which inherited MonoBehaviour.