Делаем игру на диплом, возникли проблемы с ближним боем. Если персонаж монстра бьет. то все нормально, монстр умирает. Но когда монстр атакует, то возникает ошибка
NullReferenceException: Object reference not set to an instance of an object
Enemy.OnEnemyAttack () (at Assets/Scripts/Enemy.cs:52)
Пытались решить и так, и сяк, но вообще ноль вариантов для решения.
Коды:
Код PlayerController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpForce;
private float moveInput;
public float health;
public int numOfHearts;
public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
public float heal;
public GameObject Background;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask Ground;
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if (health < numOfHearts)
{
health = numOfHearts;
}
health += Time.deltaTime * heal;
for (int i = 0; i < hearts.Length; i++)
{
if (i < Mathf.RoundToInt(health))
{
hearts[i].sprite = fullHeart;
}
else
{
hearts[i].sprite = emptyHeart;
}
if (i < numOfHearts)
{
hearts[i].enabled = true;
}
else
{
hearts[i].enabled = false;
}
if(health <= 0)
{
Background.SetActive(true);
Destroy(gameObject);
}
}
moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if (facingRight == false && moveInput > 0)
{
Flip();
}
else if (facingRight == true && moveInput < 0)
{
Flip();
}
if (moveInput == 0)
{
anim.SetBool("isRunning", false);
}
else
{
anim.SetBool("isRunning", true);
}
}
private void Update()
{
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, Ground);
if(isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = Vector2.up * jumpForce;
}
if(isGrounded == true)
{
anim.SetBool("isJumping", false);
}
else
{
anim.SetBool("isJumping", true);
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}
Код HeroAttack
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroAttack : MonoBehaviour
{
private float timeBtwAttack;
public float startTimeBtwAttack;
public Transform attackPos;
public LayerMask enemy;
public float attackRange;
public int damage;
public Animator anim;
private void Update()
{
if(timeBtwAttack <= 0)
{
if (Input.GetMouseButton(0))
{
anim.SetTrigger("Attack");
}
timeBtwAttack = startTimeBtwAttack;
}
else
{
timeBtwAttack -= Time.deltaTime;
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(attackPos.position, attackRange);
}
public void OnAttack()
{
Collider2D[] enemies = Physics2D.OverlapCircleAll(attackPos.position, attackRange, enemy);
for (int i = 0; i < enemies.Length; i++)
{
Enemy enemyScript = enemies[i].GetComponent<Enemy>();
if (enemyScript != null)
{
enemyScript.TakeDamage(damage);
}
}
}
}
Код Enemy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
private float timeBtwAttack;
public float startTimeBtwAttack;
public int health;
public float speed;
public int damage;
private PlayerController player;
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
GameObject heroObject = GameObject.FindGameObjectWithTag("Hero");
if (heroObject != null)
{
player = heroObject.GetComponent<PlayerController>();
}
}
private void Update()
{
if (health <= 0)
{
Destroy(gameObject);
}
transform.Translate(Vector2.up * speed * Time.deltaTime);
}
public void TakeDamage(int damage)
{
health -= damage;
}
public void OnTriggerStay2D(Collider2D other)
{
if (other.CompareTag("Hero"))
{
if (timeBtwAttack <= 0)
{
anim.SetTrigger("Attack");
}
else
{
timeBtwAttack -= Time.deltaTime;
}
}
}
public void OnEnemyAttack()
{
if (player != null)
{
player.health -= damage;
timeBtwAttack = startTimeBtwAttack;
}
else
{
Debug.LogError("Персонаж не обнаружен");
}
}
}
На персонаже стоит тег Hero