Getting NullReferenceErrors when running game

Hello,

ive watched the video and followed the exact same steps. However i get an error when running the game. The game still works however. Im not sure what im missing here.

NullReferenceException: Object reference not set to an instance of an object
TextController.Start () (at Assets/TextController.cs:15)
NullReferenceException: Object reference not set to an instance of an object
TextController.Update () (at Assets/TextController.cs:23)

Code looks like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TextController : MonoBehaviour
{

public Text text;
// Use this for initialization
void Start()
{
    text.text = "Hello world";
}
// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        text.text = "Space key pressed";
    }
}

}

Ive tried looking at the inspector to see if i did connect the text element to the script, but that all seems in order.


Ive also tried restarting Unity. I run Unity 5.5.

Please Help.

Hey, give it a try to accessing the text manually and see how it behaves:

just add to the start method this:

void Start()
{
text = GetComponent<Text>();
text.text = "Hello World";
}

Let us know if this works

Thanks for the replay. Iā€™ve tried it but to no avail. I made a new project instead and did all the steps again and it did work this time. I have no clue why but at least i can move on now :slight_smile:

Thanks

1 Like

Sorry for not being able to help! Im glad that you managed to pass through it though! :slight_smile:

Privacy & Terms