Getting a null error for a script that's apparently properly referenced.

I have a very simple script called stats_controller. All it does is hold the current health values of a gameobject and offer public functions for reading o changing those values. Here it is:

using UnityEngine;
using System.Collections;

public class stats_controller : MonoBehaviour {
    [SerializeField]int _health = 0;

    public int current_health() {
        return _health;
    }

    public void change_health(int value) {
        _health += value;
    }

	
}

The plan is to reference this script from other scripts to track that gameobject’s health and make changes when neccesary. In this case, I’m trying to reference it form the same gameobject. So in my second script I made a public reference to it like this:

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

public class base_controller : MonoBehaviour {
    public stats_controller sc;
    public Image bar;
    int _maxHealth = 500;
    int _cHealth;
    float fill = 1;
	void Start () {
    }

    float healthPercent(float c_health, float m_health)
    {
        return c_health / m_health;
    }

    void Update () {
        Debug.Log(sc.name);
        //_cHealth = sc.current_health();  it was giving me error here so I logged for testing


    }
}

I was getting reference errors when calling “_cHealth = sc.current_health()” so I threw in a debug line to read if it was referenced properly. When i run now, it logs the name of the object it’s connected to (as is expected) and then errors out with a null reference error. I have also tried simply searching for the componant instead of making it public and sticking it in via the editor, but the result is the same. What’s going on here?

Well the whole point of creating functions to return object values is to avoid having public variables, thus allowing you to dictate how those values can be handled. Having the functions be public should be all that’s required for them to return any values necessary. I’ve never had any trouble returning private variables via a public function.

That all being said, I addressed my problem by setting an initial value for _cHealth and having a null check before accessing my referenced script.

if (sc != null){
     _cHealth = sc.current_health();
}

For whatever reason, there seems to be a delay between making the reference and then having it be accessible, so this allows for that delay before things finally go as planned.