I’m trying to add damage when an enemy touches you in my game, but it keeps putting this NullReferenceException error. The actual damage and health bar stuff works the way I want it to without anything wrong actually happening in the game, but the error still appears in my console. Here is my code
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour
{
public Transform target;
public float speed = 4f;
public LayerMask whatIsPlayer;
public float sightRange;
public float health = 50f;
public int ouchies = 20;
public bool playerInSightRange;
Rigidbody rig;
private void Start()
{
target = GameObject.Find("Sourkid").transform;
rig = GetComponent<Rigidbody>();
}
private void Update()
{
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
if (playerInSightRange) Attack();
}
private void Attack()
{
Vector3 pos = Vector3.MoveTowards(transform.position, target.position, speed * Time.fixedDeltaTime);
rig.MovePosition(pos);
transform.LookAt(target);
}
private void OnTriggerEnter(Collider other)
{
other.gameObject.GetComponent<helth>().getHurt(ouchies);
}
public void TakeDamage (float amount)
{
health -= amount;
if (health <= 0f)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class helth : MonoBehaviour
{
public Slider slider;
public int maxHealth = 100;
public int currentHealth;
public helth helthBur;
private void Start()
{
currentHealth = maxHealth;
//helthBur.SetMaxHealth(maxHealth);
}
public void SetMaxHealth(int health)
{
slider.maxValue = health;
slider.value = health;
}
public void SetHealth(int health)
{
slider.value = health;
}
public void getHurt(int ouchies)
{
currentHealth -= ouchies;
helthBur.SetHealth(currentHealth);
}
}