I’m getting the following error and I can’t work out why. It doesn’t seem to impact the game at all - everything works, it’s just annoying.
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.OnGUI () (at Assets/Scripts/PlayerMovement.cs:177)
The error relates to the line that references actualDialogueLength - I’ve written XXXXX to the side. If I delete that part of the code, the same error comes up for the following two lines that reference actualDialogueLength.
public static int actualDialogueLength;
public static string currentDialogue;
public static string actualText;
void OnGUI ()
{
//set dialogue text
if (actualDialogueLength < currentDialogue.Length) //XXXXX
{
actualDialogueLength += 1;
}
//draw the underscore
if (underscore == 0)
actualText = currentDialogue.Substring(0, actualDialogueLength);
else
actualText = currentDialogue.Substring(0, actualDialogueLength) + "_";
}
I don’t know why you’d get an error for the int, as that should default to 0 if you didn’t populate it, I believe (it least it does when I test outside of Unity in C#… I can’t test in Unity currently), but doing Length on a string you didn’t initialize would give that NullReference exception though.
Do something like this in your if, and/or initialize your string/int:
if (!string.IsNullOrEmpty(currentDialogue) && actualDialogueLength < currentDialogue.Length)
Edit: Didn’t see John’s post before mine, that would solve the issue as well.
In my experience, this usually means that your script exists on an object you didn’t expect it to - it got added to it at some point by mistake. And those string variables will be null until the component is viewed in the Inspector, which would explain your issue.
Search for your component in your Hierarchy, I guarantee there’s a stray one hanging out causing this error.
Agree that currentDialogue is most likely where the error is. Ints that aren’t nullable can’t be null, and since you say the error is on all the lines where currentDialogue is, that would seem to hold true. So as suggested, set a default value of an empty string.
BTW, for the OP, I find that right clicking on your script in the Project Explorer and selecting Find References in Scene (I think that’s what it says?? I don’t have Unity on this PC) makes it easy to find anywhere where your script has been attached.