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?