Why am I getting a null reference error?

I have a database/login setup in Unity, and have this piece of code that runs when a correct password and username is entered.

However, I keep getting a NullReferenceException error midway through the login process. Here is my code:

IEnumerator sendLoginRequest(string username, string password)
    {

        if (isDatabaseSetup == true)
        {

            IEnumerator e = DatabaseControl.DCF.Login(username, password);
            while (e.MoveNext())
            {
                yield return e.Current;
            }

            WWW returned = e.Current as WWW;

            if (returned.text == "incorrectUser")
            {
                //Account with username not found in database
                login_error.text = "Username not found";
                part = 0; //back to login UI
            }
            if (returned.text == "Success")
            {
                //Password was correct
                blankErrors();
                part = 2; //show logged in UI

                //blank username field
                input_login_username.text = ""; //password field is blanked at the end of this function, even when error is returned

                UserAccountManager.instance.LogIn(username, password);
            }
            if (returned.text == "incorrectPass")
            {
                //Account with username found, but password incorrect
                part = 0; //back to login UI
                login_error.text = "Incorrect Password";
            }
            if (returned.text == "ContainsUnsupportedSymbol")
            {
                //One of the parameters contained a - symbol
                part = 0; //back to login UI
                login_error.text = "Unsupported Symbol '-'";
            }
            if (returned.text == "Error")
            {
                //Account Not Created, another error occurred
                part = 0; //back to login UI
                login_error.text = "Database Error. Try again later.";
            }

            //blank password field
            input_login_password.text = "";


        }
    }

And here is the error message I get:

NullReferenceException: Object reference not set to an instance of an object
LoginMenu+c__Iterator0.MoveNext () (at Assets/Scripts/LoginMenu.cs:160)

The specific line it mentions (160) is this:

 if (returned.text == "incorrectUser")

Any idea how to get rid of this error?

It seems like “returned” is null.

This means that e.Current is some type that cannot be cast to WWW. If you cast something that cannot be cast it simply defaults to null. I would check what e.Current even is and go from there.

Try:

Debug.Log(e.Current.GetType());