- Home /
Error when passing string for message function?
I've been trying to add a little GUI element in the corner of the screen where I could display messages to the player telling him that he's been spotted, or that one of his crew have completed the objective you've set them. I assumed it'd be an easy kind of inherit a class and then use a Message function in that class to change the string from a different script, yet, I'm getting this error:
NullReferenceException MessageSystem.Message (System.String m) (at Assets/Scripts/MessageSystem.cs:18) DoorOpening.Update () (at Assets/Scripts/DoorOpening.cs:10)
Here's both of the scripts that are throwing the exception:
The Message method.
GameObject line1;
GUIText line1Text;
void Update()
{
line1 = GameObject.Find ("Line1");
line1Text = line1.GetComponent<GUIText>();
}
public void Message(string m = "")
{
line1Text.text = m;
}
The method where I call Message.
public class DoorOpening : MessageSystem {
void Update()
{
if(Input.GetKeyDown("m"))
{
Message("Locked.");
}
}
}
I really have no idea why the reference is null. I'm providing a reference to the method in the Update of the DoorOpening script.
Unless the your GUIText object can be destroyed, there is no reason to do the Find() and GetComponent() in Update(). Do it in Start(). As for your problem:
$$anonymous$$ake absolutely sure that the game object with the GUIText is named (not tagged) 'Line1' exactly. Not 'line1' or 'Line 1' or '1ine1'.
$$anonymous$$ake absolutely sure that there is a GUIText component on the 'Line1' named game object.
$$anonymous$$ake sure there are not multiple 'Line1'-named game objects in the scene.
I just checked. It seems that every single one of those is true. I've got the GUIText component on my Line1 object.
Line1 is named "Line1" exactly, to the letter.
There is only one Line1 in the whole project.
Answer by 767_2 · Oct 04, 2014 at 03:53 PM
check this
public class DoorOpening : MessageSystem {
void Start()
{
Message("");
}
void Update()
{
if(Input.GetKeyDown("m"))
{
Message("Locked.");
}
}
}
Answer by crodriguez · Oct 05, 2014 at 08:42 PM
You cannot assign something to a variable you're going to pass in a function parameter. To be more clear, you cannot do this:
public void Message(string m = "")
Instead, just insert this:
public void Message(string m)
Your answer
![](https://koobas.hobune.stream/wayback/20220613164405im_/https://answers.unity.com/themes/thub/images/avi.jpg)