Encountering problem accessing Text component

Hi all,

I am a little baffled by this one, mind you I am baffled by a lot of things these days, so one more thing won’t hurt I guess :wink:

I have added the UnityEngine.UI namespace via a “using” directive then I added a private Text class member, I tried to make it public and drag and drop the Text component to it but wasn’t able to drop it, it wouldn’t take it, the mouse icon remained “forbidden”

I then associated the private member called “_text” to the component in the “Start” function like this:
_text = GetComponentInChildren ();
and proceeded to set its text like this:
_text.text = _scoreValue.ToString ();

I have another 2 functions built by myself which can make changes to the text value of the _text member, unfortunately I cannot use _text.text = some_string;, I keep getting a NullReferenceException error: Object reference not set to an instance of an object. The only way I can change the text in these functions is to do this:
GetComponentInChildren().text = some_string;
I do not understand why I have to do this everytime and why my _text member can’t keep a reference to the text component, it’s driving me nuts.
I also don’t understand why when I make the field public I cannot drop it into the gameobject’s inspector window.

The Text component is inside a Canvas component which itself is inside the game object associated to the C# script, hence the GetComponentInChildren function used and not the GetComponent function.

Regards
Crouz

Hm… very interesting. I’m sure you are doing something wrong, but in your case it isn’t obvious.
I tried to do the same in my project, and I can simply drag and drop the Text component and it works.
There is another way to add component to variable. There is small circle next to drag and drop field. If you click there you can choose from all Text components in your project.

Unfortunately I have clicked that little circle already and I cannot see the text component at all, something must be corrupted or something.

I advise you to create completely new project, and try again.

Have you tried instead of using Text, to use UnityEngine.UI.Text?

Please post your code (using the “Insert Code…” button, in the edit bar between the movie filmstrip and the floppy disk icon).

Also post a screen shot of the Text object you’re trying to drag in, including the Inspector inspecting it. I suspect that somehow you don’t have what you think you have.