Object reference not set to an instance of an object

I get this error when trying to reference a variable from another script.

NullReferenceException: Object reference not set to an instance of an object
UIManager.Start () (at Assets/Scripts/UIManager.cs:16)

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

[RequireComponent(typeof(CharacterStats))]
public class UIManager : MonoBehaviour {

    public Text health;
    public Text armor;

    private int currentHealth;

    // Use this for initialization
    void Start () {
        GetComponent<CharacterStats>().currentHealth += currentHealth;
    }

    // Update is called once per frame
    void Update () {
        health.text = currentHealth.ToString();
    }
}

Well, in your case there is only one option. You are calling GetComponent for a CharacterStats script, which means it didn’t find that script on the same gameObject your UIManager is on.

If you read up on RequireComponent, it’s possible you had the UIManager on a gameobject before adding the RequireComponent, which means existing objects with UIManager on them already would not have had CharacterStats added to it.

So, just double check that it’s there.

Also, as a word of advice, I would not update health.text in Update. It’s pretty rare you need to update text every frame and instead should just update the text when the value changes.