Why I can't reference this string ?


I have two scripts in C# and I’m trying to reference from one script the string from another script like this :

SettingUpLocations setup=(SettingUpLocations)GetComponent("SettingUpLocations");

In the script SettingUpLocations I have the string : levelName being setup like this :

public string levelName = "";

And I assign the level name through the inspector. Why when I try to reference it in game I receive the error :

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

I referenced hundreds of variables like this, but this is the first it gives me this problem.


Because if you’re just saying (setup.levelName), that’s trying to call a static variable, when you just have a public one. If you want to access it this way, make it (public static) instead of just public. If you want to keep it just public, you would need to access it via GetComponent. Say you have your current script attached to a gameObject named (scripts) just for example’s sake. You would use:

GameObject scripts;

void Start()
    scripts = GameObject.Find("scripts");
    string lvl = scripts.GetComponent<setup>().levelName;

For more help, check out the GetComponent Reference.

Change the code to this:

SettingUpLocations setup = GetComponent<SettingUpLocations>();
if (setup == null) {
    Debug.LogError("Failed to get SettingUpLocations component!");
} else {
    Debug.Log("Loading level " + setup.levelName);

I bet you’re getting the NullReferenceException because GetComponent() returns null.