My game has a weird null exception error that I keep on getting everytime I start the game. It only appears once in the console window.
NullReferenceException: Object reference not set to an instance of an object
StatusIndicator.Awake () (at Assets/Scripts/StatusIndicator.cs:15)
StatusIndicator.cs:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class StatusIndicator : MonoBehaviour
{
[SerializeField] private RectTransform healthBarRect;
private Quaternion rotation;
private Vector3 position;
void Awake()
{
rotation = transform.rotation;
position = transform.parent.position - transform.position;
}
void Update()
{
transform.rotation = rotation;
transform.position = transform.parent.position - position;
}
public void SetHealth(float _cur, float _max)
{
float value = _cur / _max;
healthBarRect.localScale = new Vector3(value, healthBarRect.localScale.y, healthBarRect.localScale.z);
}
}
Not really sure why this is happening. My game works perfectly fine even with the error. If you’re not sure what I’m doing between line 12-22, I’m restricting my StatusIndicator (health bar) to rotate with the parent (enemy) and also make sure position is aligned correctly. If anyone have any idea why it’s happening, let me know.
The only explanation for this exception is if transform.parent is null (but this exception would leave position uninitialized, unless you set its value somewhere else in the code).
The exception is thrown if your StatusIndicator doesn’t have a parent transform. None of the code you have shown is setting the parent, so this is happening due to something else.