- Home /
The problem is into first script, Update function. I cant achieve _player.CurrentHealth and cant understand why. Help pls
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
[RequireComponent(typeof(Slider))] public class HealthBar : MonoBehaviour { [SerializeField] private float _smoothness; private Player _player; private Slider _slider;
private void Start()
{
Debug.Log(_player.CurrentHealth);
}
public void SetMaxHealth(float health)
{
_slider = GetComponent<Slider>();
_slider.maxValue = health;
_slider.value = health;
}
public void SetHealth(float health)
{
_slider.value = health;
}
private void Update()
{
if (_slider.value != _player.CurrentHealth)
_slider.value = Mathf.Lerp(_slider.value, _player.CurrentHealth, _smoothness * Time.deltaTime);
}
}
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Player : MonoBehaviour {
[SerializeField] private float _maxHealth; [SerializeField] private HealthBar _healthBar;
private float _currentHealth;
public float CurrentHealth => _currentHealth;
private void Start()
{
_currentHealth = _maxHealth;
_healthBar.SetMaxHealth(_maxHealth);
}
public void ChangeHealth(float health)
{
_currentHealth = health;
if (health < 0)
{
_currentHealth = 0;
}
else if (health > _maxHealth)
{
_currentHealth = _maxHealth;
}
_healthBar.SetHealth(_currentHealth);
}
}
Answer by andrey231102 · Aug 02, 2021 at 08:36 PM
oh sorry, it was easy, i forgot to attach my player to the 1 script(with serializefield)
Your answer
Follow this Question
Related Questions
Referencing instantiated objects at runtime 2 Answers
Reference by Instance ID? 2 Answers
Object reference not set to an instance of an object 3 Answers
How can I replace an object while keeping the references to that object? 2 Answers
Retain references to child gameobjects while duplicating objects 0 Answers