运行状况滑块(如果启用了语句行渲染器)

时间:2019-02-05 03:40:17

标签: c# if-statement unity3d uislider raycasting

“我的敌人”脚本在播放器范围内时会激活光线投射和线条渲染器。但是,在敌人被摧毁或将玩家移出范围后,使用我的健康滑块下面的“健康”脚本会继续降低其价值。

统一的新手,希望这不是太简单。我想它的原因是CurrentHealth -= Time.deltaTime * 10;之后没有什么可以阻止健康下降,但是我该如何解决呢?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Health : MonoBehaviour
{
    public Text HealthText;
    public Slider HealthSlider;

    public float MaxHealth = 100;
    static public float CurrentHealth = 100;

    public LineRenderer lineRenderer;

    private void Update()
    {
        HealthUI();

        if (CurrentHealth > 0)
        {
            if (lineRenderer.enabled) 
            {
                CurrentHealth -= Time.deltaTime * 10;   
            }
        }
    }   

    public void HealthUI()
    {
        HealthSlider.value = CurrentHealth / MaxHealth;
        HealthText.text = "HEALTH " + ((int)(CurrentHealth / MaxHealth * 100)).ToString() + "%";
    }  
}

谢谢!

1 个答案:

答案 0 :(得分:0)

除非从另一个脚本修改了CurrentHealth,否则运行状况降低的唯一原因是未禁用引用的行渲染器。因此,请确保您引用了正确的线条渲染器,并且在附近没有敌人的情况下将其禁用。

请注意,您当前的方法仅需要一个线渲染器即可打开和关闭,这取决于敌人是否在视线范围内。这会变得凌乱。我认为更好的方法是在玩家看到时直接在运行状况脚本上调用TakeDamage方法:

using UnityEngine;
using UnityEngine.UI;

public class Health : MonoBehaviour
{
    public Text HealthText;
    public Slider HealthSlider;

    public float MaxHealth = 100;
    public float CurrentHealth = 100;

    public void TakeDamage()
    {
        if (CurrentHealth > 0)
        {
            CurrentHealth -= Time.deltaTime * 10;
        }
    }

    private void Update()
    {
        HealthUI();
    }

    public void HealthUI()
    {
        HealthSlider.value = CurrentHealth / MaxHealth;
        HealthText.text = "HEALTH " + ((int)(CurrentHealth / MaxHealth * 100)).ToString() + "%";
    }
}