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.
Answer by vsetka · Oct 11, 2015 at 12:40 PM
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've done that and I can see that field is turning up Null, with the same error as above. I don't understand how to fix it though. I've tested levelName and it matches the variable name in the manager GameObject's script (Script_Game$$anonymous$$anager).
Is your field public? If not, try specifying the binding flags https://msdn.microsoft.com/en-us/library/4ek9c21e(v=vs.110).aspx
I think so, as the class and int are both public, as per the example in the reference you linked.
public class Script_Game$$anonymous$$anager : $$anonymous$$onoBehaviour
{
public int lvlGame = 3;
}
I've tried specifying all possible binding flags and it hasn't helped.
Answer by OpaqueAmber · Oct 11, 2015 at 03:22 PM
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.
I know this is an old post but to help clarify GetValue() needs to be passed an instance of the type for which you get field info in reflection.