I have been running into this issue for past few days where im supposed have enemy attack the player and player loses health via slider healthbar like in Surival shooter tutorial I went over the code but unsure whats wrong. the error shows up NullReferenceException: Object reference not set to an isntance of an object Attack.Awake()(at Assets/Attack.cs:19) i makred below with // where error is at
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attack : MonoBehaviour {
public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;
Animator anim;
GameObject player;
PlayerHealthBar cyclopsHealth;
enemyHealth enemyHealth;
bool playerInRange;
float timer;
// Use this for initialization
void Awake () {
player = GameObject.Find("Player");
cyclopsHealth = player.GetComponent<PlayerHealthBar>(); //error appears here
enemyHealth = GetComponent<enemyHealth>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void OnTriggerEnter(Collider other)
{
if(other.gameObject == player)
{
playerInRange = true;
}
}
private void OnTriggerExit(Collider other)
{
if(other.gameObject == player)
{
playerInRange = false;
}
}
void Update () {
timer += Time.deltaTime;
if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
{
Attacks ();
}
if(cyclopsHealth.currentHealth <= 0)
{
anim.SetTrigger("Death");
}
}
void Attacks()
{
timer = 0f;
if(cyclopsHealth.currentHealth > 0)
{
cyclopsHealth.TakeDamage(attackDamage);
}
}
}
the code below this is the player health script incase that be need to assist
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealthBar : MonoBehaviour {
public int startingHealth = 100;
public int currentHealth;
public Slider healthBar;
public AudioClip ScreamsShouts_Monster_Processed;
Animator anim;
AudioSource playerAudio;
Cyclop_Player_Controller playerMovement;
bool isDead;
private void Awake()
{
anim = GetComponent<Animator>();
playerAudio = GetComponent<AudioSource>();
playerMovement = GetComponent<Cyclop_Player_Controller>();
// playerAttack = GetComponentInChildren <PlayerAttacking> ();
currentHealth = startingHealth;
}
public void TakeDamage (int amount)
{
currentHealth -= amount;
healthBar.value = currentHealth;
playerAudio.Play();
if(currentHealth <= 0 && !isDead)
{
Die();
}
}
void Die()
{
isDead = true;
//playerAttacking.DisableEffects();
anim.SetTrigger("Die");
playerAudio.clip = ScreamsShouts_Monster_Processed;
playerAudio.Play();
playerMovement.enabled = false;
// playerAttacking.enabled = false;
}
}