首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >健康条与健康代码脚本同步

健康条与健康代码脚本同步
EN

Stack Overflow用户
提问于 2019-05-24 23:14:56
回答 2查看 824关注 0票数 0

我创建了一个带有健康条和脚本的UI图像,但是当我的玩家受到攻击时,健康条的图像并没有改变,只是在检查器中显示了伤害的变化。当玩家受到攻击时,如何使UI图像健康条发生变化?我需要更改脚本中的某些内容吗?

代码语言:javascript
复制
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;
    }
}
EN

回答 2

Stack Overflow用户

发布于 2019-05-24 23:27:23

我看到了两个问题。

当玩家受到伤害时,

  1. 你的方法UpdateHealthBar不会被调用。一种解决方案是在DamagePlayer方法的末尾调用该方法。(请注意,虽然Update将在每一帧都被调用,但UpdateHealthBar不会。)
  2. 另外,看起来您正在使用两个变量来跟踪玩家的健康状况:hitpointcurrentHealth。这两个有什么不同?两个都需要吗?目前,在UpdateHealthbar方法中使用了hitpoint,但在DamagePlayer方法中减少了currentHealth。您需要这两种方法为健康条使用相同的变量,以准确地反映玩家的健康状况。
票数 2
EN

Stack Overflow用户

发布于 2019-05-24 23:40:58

为了你的玩家健康,使用ScriptableObject

this Unity Blog中有一篇关于ScriptableObject的很好的文章描述了这个困境。基本上,ScriptableObject是一个资产(也可以实例化,在运行时创建),可以由多个组件使用,以便它们引用相同的东西。您将在项目中创建此资产,并将其附加到播放器的健康脚本和播放器的UI脚本。当其中一个值发生更改时,它将反映在另一个中。附加的价值是您分离了您的关注点(并删除了许多单例的用例)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56295381

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档