Search code examples
unity-game-enginesingletongameobject

GameObject gets dropped when game is in play mode "NullReferenceException object reference not set an instance or object"


I have an empty object called TimeManager. On the object I have attached the following script. I then dragged the text UI GameObject "MyTime" to the Text Timer field. When the game is not playing everything shows up. When I hit play the object becomes unassigned.

If while game is playing, I can drag the "MyTime" to the Text Timer and then it works fine. I am not sure why it is dropping when I hit play.

public class TimeLeft : MonoBehaviour
{


public float myCoolTimer = 10;
public Text timerText;

public static TimeLeft instance = null;

void Awake ()
{
    if (instance == null) {
        instance = this;
    } else if (instance != this) {
        Destroy (this.gameObject);
    }

}

void Start ()
{
    timerText = GetComponent<Text> ();

}


public void Update ()
{
    //Timer
    myCoolTimer -= Time.deltaTime;
    timerText.text = myCoolTimer.ToString ("f2");

}

Note: I need the singleton because I use it in other scripts.


Solution

  • The TimeManager object is not the same game object as the one holding the text component.

    void Start ()
    {
        timerText = GetComponent<Text> ();
    }
    

    The Start method looks for a Text component on the same object as the TimeManager and none is found so it assigns null.

    Either remove the line from the start since you are dragging the component or check if it is null and look for the object.

    void Start ()
    {
        if(timerText != null){
           GameObject timerObject = GameObject.Find("TextObjectName");
           timerText = timerObject.GetComponent<Text> ();
        }
    }