So I am very new to Unity and am following a tutorial. I am making a health bar and I am getting a NullReferenceException error on line 36. I have no idea where this could be coming from since it looks the same on his screen. The tutorial was made 2 years ago so that could have something to do with it. Since i have no experience with coding… I pasted the entire 67 line thing. Sorry if this is and inconvenience. I got the best snippet of his code that he showed… Let me know if you need anything else.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
private float health;
private float lerpTimer;
public float maxHealth = 100f;
public float chipSpeed = 2f;
public Image frontHealthBar;
public Image backHealthBar;
// Start is called before the first frame update
void Start()
{
health = maxHealth;
}
// Update is called once per frame
void Update()
{
health = Mathf.Clamp(health, 0, maxHealth);
UpdateHealthUI();
if(Input.GetKeyDown(KeyCode.X))
{
TakeDamage(Random.Range(5, 10));
}
if(Input.GetKeyDown(KeyCode.Z))
{
RestoreHealth(Random.Range(5, 10));
}
}
public void UpdateHealthUI()
{
Debug.Log(health);
float fillF = frontHealthBar.fillAmount;
float fillB = backHealthBar.fillAmount;
float hFraction = health / maxHealth;
if (fillB > hFraction)
{
frontHealthBar.fillAmount = hFraction;
backHealthBar.color = Color.red;
lerpTimer += Time.deltaTime;
float percentComplete = lerpTimer / chipSpeed;
backHealthBar.fillAmount = Mathf.Lerp(fillB, hFraction, percentComplete);
}
if (fillF < hFraction)
{
backHealthBar.fillAmount = hFraction;
backHealthBar.color = Color.green;
lerpTimer += Time.deltaTime;
float percentComplete = lerpTimer / chipSpeed;
frontHealthBar.fillAmount = Mathf.Lerp(fillF, hFraction, percentComplete);
}
}
public void TakeDamage(float damage)
{
health -= damage;
lerpTimer = 0f;
}
public void RestoreHealth(float healAmount)
{
health += healAmount;
lerpTimer = 0f;
}
}
.