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?
Answer by ComradeVanti · Apr 11, 2017 at 01:15 PM
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());
I tried what you suggested, and the debug log returns 'System.String.' I don't know what that means for the error?
Im not really familiar with WWW but can you cast a string to a WWW? If so i dont understand the error either. But if you cant cast a string to a WWW that makes more sense.
Its like doing this:
SpriteRenderer renderer = (SpriteRenderer)myPolygonCollider2D;
C#/Unity cant handle that and makes it null.
Your answer
Follow this Question
Related Questions
Null Reference in UnityStandardAssets.Utility.WaypointProgressTracker.Update 0 Answers
NullRefrenceException: Object refrence not set to an instance of an object. 0 Answers
Need some help with networking, Object reference not set to an instance of an object. 0 Answers
null reference exception help 1 Answer