Gameobject reference disappears at start
My game has objects falling and the player moves (a cauldron) to collect them and gain points. I am trying to make a Slider into a progress bar by setting its value equal to the score. I also have some text above it that specifically states the number of points.
Here is the relevant code for that:
var progressSlider : UI.Slider;
var pointsText : UI.Text;
public var points : int = 0;
public var finished : boolean = false;
function Awake() {
progressSlider = GetComponent(UI.Slider);
pointsText = GetComponent(UI.Text);
}
function Update () {
CountPoints();
}
function OnCollisionEnter2D (other : Collision2D) {
if (other.gameObject.CompareTag("B-Ingredient")) {
other.gameObject.SetActive(false);
points = points + 5;
} else if (other.gameObject.CompareTag("S-Ingredient")) {
other.gameObject.SetActive(false);
points = points - 5;
}
}
function CountPoints () {
progressSlider.value = points; //this is the line that the NullReferenceException refers to
if (points >= 50) {
finished = true;
}
pointsText.text = "Points: " + points.ToString;
}
Note: the collision enter stuff refers to a Rigidbody that's in the script, but I took it out to make it more focused on the problem. The collision stuff definitely isn't the problem.
I used Debug.Log and found that the references to progressSlider and pointsText are returning null, and I understand why (sorta). I assigned the slider and text their GameObjects in the inspector, but once I start the game, they disappear from the inspector:
I'm wondering if this is a bug. In this script (not shown in the code portion), I call for a Rigidbody and that Rigidbody doesn't disappear at the start or return null. In Play Mode, I tried re-assigning the references (as in dragging the Slider and Text objects in their respective reference boxes) and it works exactly how I want it to after.
Does this have to do with how I called GetComponent for the UI elements or the fact that they're children of the Canvas object? Any help (even if it's just general code fixes) would be appreciated!
Answer by AurimasBlazulionis · Dec 31, 2016 at 04:49 AM
You try to get progress slider and text on awake. You do not need that. This is the reason you get these removed. Remove the awake method.
Thanks so much, you're a lifesaver! This worked perfectly :)