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

Hi,

I’ve been trying to figure out how to load a level by referencing an int that’s a variable in a different object’s script, but I’m doing something wrong.

I’m passing in the name of the int through the inspector and trying to use reflection:

private GameObject manager;

public void ClickAsync(string levelName)
{
    manager = GameObject.Find("GameManager");

    int levelValue = (int)manager.GetType().GetField(levelName).GetValue(manager);

    loadingImage.SetActive(true);
    StartCoroutine(LoadLevelWithBar(levelValue));
}

I’m getting this error:

NullReferenceException: Object reference not set to an instance of an object
Script_ClickToLoadAsync.ClickAsync (System.String levelName) (at Assets/scripts/Script_ClickToLoadAsync.cs:19)

Line 19 is this line:

int levelValue = (int)manager.GetType().GetField(levelName).GetValue(manager);

Could someone please explain to me what I’m doing wrong and how to solve this?

Thank you in advance for your assistance.

Try to split that sausage up and identify the null reference. Try something like:

Type type = manager.GetType();
FieldInfo field = type.GetField(levelName);
object value = field.GetValue(manager);
int levelValue = (int)value;

Of course, make sure manager and levelName are not null, and if not, you’ll easily identify which Get… fails to find what you’re looking for.

I figured out what I was doing wrong.

int levelValue = (int)manager.GetType().GetField(levelName).GetValue(manager);

Should have been:

int levelValue = (int)manager.GetComponent<Script_GameManager>().GetType().GetField(levelName).GetValue(manager.GetComponent<Script_GameManager>());

This is why my field was turning up Null.