我创建了一个带有健康条和脚本的UI图像,但是当我的玩家受到攻击时,健康条的图像并没有改变,只是在检查器中显示了伤害的变化。当玩家受到攻击时,如何使UI图像健康条发生变化?我需要更改脚本中的某些内容吗?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class HealthBar : MonoBehaviour
{
public static HealthBar singleton;
public Image currentHealthbar;
public Text ratioText;
public float currentHealth;
public float maxHealth = 100f;
public bool isDead = false;
public bool isGameOver = false;
public GameObject gameOverText;
private void Awake()
{
singleton = this;
}
// Start is called before the first frame update
private void Start()
{
currentHealth = maxHealth;
UpdateHealthbar();
}
// Update is called once per frame
private void UpdateHealthbar()
{
float ratio = currentHealth/ maxHealth;
currentHealthbar.rectTransform.localScale = new Vector3(ratio, 1, 1);
ratioText.text = (ratio * 100).ToString("0") + '%' ;
}
void Update()
{
if(currentHealth < 0)
{
currentHealth = 0;
}
}
public void DamagePlayer(float damage)
{
if(currentHealth > 0)
{
currentHealth -= damage;
}
else
{
Dead();
if (isGameOver && Input.GetMouseButtonDown(0))
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
UpdateHealthbar();
}
void Dead()
{
currentHealth = 0;
isDead = true;
Debug.Log("Player is dead");
gameOverText.SetActive(true);
isGameOver = true;
}
}发布于 2019-05-24 23:27:23
我看到了两个问题。
当玩家受到伤害时,
UpdateHealthBar不会被调用。一种解决方案是在DamagePlayer方法的末尾调用该方法。(请注意,虽然Update将在每一帧都被调用,但UpdateHealthBar不会。)hitpoint和currentHealth。这两个有什么不同?两个都需要吗?目前,在UpdateHealthbar方法中使用了hitpoint,但在DamagePlayer方法中减少了currentHealth。您需要这两种方法为健康条使用相同的变量,以准确地反映玩家的健康状况。发布于 2019-05-24 23:40:58
为了你的玩家健康,使用ScriptableObject
在this Unity Blog中有一篇关于ScriptableObject的很好的文章描述了这个困境。基本上,ScriptableObject是一个资产(也可以实例化,在运行时创建),可以由多个组件使用,以便它们引用相同的东西。您将在项目中创建此资产,并将其附加到播放器的健康脚本和播放器的UI脚本。当其中一个值发生更改时,它将反映在另一个中。附加的价值是您分离了您的关注点(并删除了许多单例的用例)。
https://stackoverflow.com/questions/56295381
复制相似问题