invoke method with reflection C#

using UnityEngine;
using System.Collections;
using System;
using System.Reflection;

public class blblb : MonoBehaviour
{

    void Start()
    {
        Type thisType = this.GetType();
        MethodInfo theMethod = thisType.GetMethod("bla");
        theMethod.Invoke(this, null);
    }

    private void bla()
    {
        Debug.Log("enters");
    }
}

NullReferenceException: Object
reference not set to an instance of an
object blblb.Start () (at
Assets/blblb.cs:13)

What am I doing wrong to get this error?

P.S I know there’s Invoke method in unity. I need to know how to use the reflection way.

This is an example on how to get instance methods. It works for me so there is no reason it should break for you.

private Action myAction = ()=>{};

void Start()
{
   System.Type ourType = this.GetType(); 

   MethodInfo mi= ourType.GetMethod("MyMethod", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
        
   if (mi!= null){
       myAction = (Action)Delegate.CreateDelegate(typeof(Action), this, mi);
   }
} 

then you can call myAction(); like any other methods.

This has the advantage of allowing sub class to contain methods or not just like Unity does for Update/LateUpdate or other events. Your top class may contain all the checks and the sub class just implements or not.

msdn documentation on GetMethod().

“Searches for the public method with the specified name.”

Simply make your bla method public :wink:

Note:
The easiest way to debug this kind of stuff is to use Debug.Log() statements.

void Start ()
{
	Type thisType = this.GetType();

	Debug.Log ("Type: " + thisType);

	MethodInfo theMethod = thisType.GetMethod("bla");

	Debug.Log ("MethodInfo: " + theMethod);

	theMethod.Invoke(this, null);
}

theMethod variable is null, since the bla method is private and cannot be found (hence the NullReferenceException).

Well first of all, don’t type “this”, because thats just going to cause errors…

Change your code to:

Invoke (“YourFunction”, 0);

assuming the name of your function is YourFunction.