题外Tips:
Unity Editor中可以设置是 Pivot模式 或者 Center 模式
Alt + click 视图里的GameObject,可展开所有子项。
实现效果:
Canvas 渲染模式选择 World Space,Rect 才可以调整,默认是不可以的。
Slider控制血量的显示,删除 Handle Slide Area,去掉Interactable的对勾,就可阻止用户修改血量,而只能显示。
TankExplosion uncheck Play On Awake,初始化的时候不执行 该粒子效果
也可以使用 Object pooling 控制对象的初始化和回收
m_ExplosionParticles = Instantiate(m_ExplosionPrefab).GetComponent<ParticleSystem>();
m_ExplosionAudio = m_ExplosionParticles.GetComponent<AudioSource>();
m_ExplosionParticles.gameObject.SetActive(false);
TankHealth.cs:
using UnityEngine;
using UnityEngine.UI;
public class TankHealth : MonoBehaviour
{
public float m_StartingHealth = 100f;
public Slider m_Slider;
public Image m_FillImage;
public Color m_FullHealthColor = Color.green;
public Color m_ZeroHealthColor = Color.red;
public GameObject m_ExplosionPrefab;
private AudioSource m_ExplosionAudio;
private ParticleSystem m_ExplosionParticles;
private float m_CurrentHealth;
private bool m_Dead;
private void Awake()
{
m_ExplosionParticles = Instantiate(m_ExplosionPrefab).GetComponent<ParticleSystem>();
m_ExplosionAudio = m_ExplosionParticles.GetComponent<AudioSource>();
m_ExplosionParticles.gameObject.SetActive(false);
}
private void OnEnable()
{
m_CurrentHealth = m_StartingHealth;
m_Dead = false;
SetHealthUI();
}
public void TakeDamage(float amount)
{
// Adjust the tank's current health, update the UI based on the new health and check whether or not the tank is dead.
m_CurrentHealth -= amount;
SetHealthUI();
if (m_CurrentHealth <= 0f && !m_Dead){
OnDeath();
}
}
private void SetHealthUI()
{
// Adjust the value and colour of the slider.
m_Slider.value = m_CurrentHealth;
m_FillImage.color = Color.Lerp(m_ZeroHealthColor,m_FullHealthColor,m_CurrentHealth / m_StartingHealth);
}
private void OnDeath()
{
// Play the effects for the death of the tank and deactivate it.
m_Dead = true;
m_ExplosionParticles.transform.position = transform.position;
m_ExplosionParticles.gameObject.SetActive(true);
m_ExplosionParticles.Play();
m_ExplosionAudio.Play();
gameObject.SetActive(false);
}
}