Не отображается HP бар на объекте в Unity2D
У меня есть на объекте ХП Бар, но когда я запускаю игровую сцену, то ХП БАР отключается. Если я попытаюсь включить, то при попадания пули он снова отключается.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Enemy : MonoBehaviour
{
[SerializeField] private int _health;
[SerializeField] private int _reward;
public Player _target;
private Animator _animator;
private int _currentHealth;
public HealthBarEnemy HealthBar;
public int Reward => _reward;
public Player Target => _target;
public event UnityAction<Enemy> Dying;
private void Start()
{
_animator = GetComponent<Animator>();
_currentHealth = _health;
HealthBar.SetHealth(_currentHealth, _health);
}
public void Init(Player target)
{
_target = target;
}
public void TakeDamage(int damage)
{
_health -= damage;
HealthBar.SetHealth(_currentHealth, _health);
if (_health <= 0)
{
Dying?.Invoke(this);
_animator.SetTrigger("Death");
Destroy(gameObject);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBarEnemy : MonoBehaviour
{
public Slider Slider;
public Color Low;
public Color High;
public Vector3 Offset;
public void SetHealth(int health, int maxHealth)
{
Slider.gameObject.SetActive(health < maxHealth);
Slider.value = health;
Slider.maxValue = maxHealth;
Slider.fillRect.GetComponentInChildren<Image>().color = Color.Lerp(Low, High, Slider.normalizedValue);
}
void Update()
{
Slider.transform.position = Camera.main.WorldToScreenPoint(transform.parent.position + Offset);
}
}
Ответы (1 шт):
Автор решения: immorom
→ Ссылка
В TakeDamage() урон отнимается от _health, хотя явно должен от _currentHealth. Не забудь еще об if'е там же.
Чтобы не путаться, лучше переименуй _health в что-то вроде _maxHealth, как это у тебя в принципе и написано в параметрах к SetHealth().

