NoReferenceException ... OnCollisionEnter
So sorry for this post since I believe this is a perhaps easily fixable error, but there were no other posts that were helpful.
What I am trying to do here is damage the player through collision by colliding into the player and then damage the health of the player. But for some reason, I am getting this Error.
NullReferenceException: Object reference not set to an instance of an object GreenSlime.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/Scripts/Enemy/GreenSlime.cs:31)
public class GreenSlime : MonoBehaviour, IEnemy {
public float currentHealth, power, toughness;
public float maxHealth;
private int damageValue = 10;
PlayerHealth playerHealth;
GameObject player;
void Start()
{
currentHealth = maxHealth;
}
public void PerformAttack()
{
throw new NotImplementedException();
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
playerHealth.currentHealth = damageValue;
playerHealth.playerHealthBar.value = playerHealth.currentHealth;
}
public void TakeDamage(int amount)
{
currentHealth -= amount;
if (currentHealth <= 0)
Die();
}
void Die()
{
Destroy(gameObject);
}
}
Thanks for the Help!
where is playerHealth
assigned? you need to supply the reference from somewhere...
Well I did make Playerhealth playerHealth;
Where the PlayerHealth is the other script I am using to get the currentHealth.
you need to get a reference to the GameObject/Component
. something like:
collision.GetComponent<PlayerHealth>().currentHealth = damageValue;
but if you're referencing the component in many places, store it in a temporary variable - GetComponent calls aren't fast.