Witam
Tworze w Unity pierwsza grę, w dużej mierze opartą na poradnikach z ich strony.Tworząc system ataku na gracza natrafiłem na probłem, z którym sam sobie nie potrafię poradzić.
Otóż, gdy przeciwnik próbuje zaatakować gracza występuję błąd opisany nastepującymi słowami: Object reference not set to an instance of an object GhostAI.Attack()
Kod wygląda następująco:
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int baseHealth;
public int currentHealth;
public bool damaged;
void Awake () {
currentHealth = baseHealth;
}
void Update () {
}
void Death() {
Debug.Log("Player is dead.");
}
public void TakingDamage(int damage) {
currentHealth -= damage;
if (currentHealth <=0)
Death();
}
}
Druga klasa opisująca zachowanie przeciwnika:
using UnityEngine;
using System.Collections;
public class GhostAI : MonoBehaviour {
public int baseHealth;
public int currentHealth;
public int attackDamage;
public bool playerInRange;
public float timer;
GameObject player;
PlayerHealth playerHealth;
void Awake() {
currentHealth = baseHealth;
player = GameObject.FindGameObjectWithTag ("Player");
playerHealth = player.GetComponent <PlayerHealth> ();
}
void Update () {
timer +=Time.deltaTime;
if (playerInRange)
{
Attack();
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player")){
playerInRange = true;
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player")){
playerInRange = false;
}
}
void Attack()
{
timer = 0f;
if (playerHealth.currentHealth >0)
{
playerHealth.TakingDamage(attackDamage);
}
}
}
Jeżeli ktoś miałby jakiś pomysł, to proszę o odpowiedź. Z góry dziękuję.