Hello more experienced coders! I've run into this C# error in Unity and have been unable to understand why. I'm an absolute beginner, so even when reading other answers here, I haven't been able to grasp how or why any of the solutions work or how to implement them. Here's what I've got.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthStatusBar : MonoBehaviour
{
public PlayerController mainHealth;
public Image fillImage;
private Slider slider;
void Awake()
{
slider = GetComponent<Slider>();
}
// Update is called once per frame
void Update()
{
float fillValue = PlayerController.mainHealth / PlayerController.maxHealth;
slider.value = fillValue;
}
}
The script above is giving me the problem. This line specifically.
float fillValue = PlayerController.mainHealth / PlayerController.maxHealth;
slider.value = fillValue;
Here's the relevant portion from my other script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpForce;
private float moveInput;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJumps;
public int extraJumpValue;
//Health
public int mainHealth;
public int maxHealth;
//Health
void Awake()
{
mainHealth = maxHealth;
}
I've tried making mainHealth and maxHealth static which fixes the error, but that removes the ability to change the value in Unity's editor. I'm sure this is a super simple solution, but this is the second time I've encountered this error and have been unable to resolve it. If anyone can explain this in better detail, that would be greatly appreciated.
Edit: The CS0120 error has been resolved. PlayerController.mainHealth needed to be changed to mainHealth.mainHealth. However, I am now getting a Null Reference Exception from the same troublesome line of code.