每当他与敌人的激光碰撞时,我都试图降低其健康状况,但是我编写的脚本无法正常工作,并且给我以下错误:


  资产/脚本/激光/HealthManager.cs(19,21):错误CS0029:无法将类型void隐式转换为UnityEngine.UI.Slider。


有人可以花一些时间查看我的代码并告诉我Healthbar为什么不起作用吗?谢谢。

HealthManager脚本:

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

public class HealthManager : MonoBehaviour {
public int CurrentHealth { get; set; }
public int MaxHealth { get; set; }
public Slider HealthBar;
//public GameObject LaserBulletEnemyPreFab;
//public GameObject PlayerPrefab;
//public LaserLevelManager myLevelmanager;

// Use this for initialization
void Start () {

    MaxHealth = 20;
    CurrentHealth = MaxHealth; //Resseting the health on start
    HealthBar = CalculatingHealth();

}

// Update is called once per frame
void Update()
{
    if(GetComponent<Collider>().gameObject.tag == "EnemyLaser")
    {
        Destroy(GetComponent<Collider>().gameObject);
        DealDamage(1);
    }
}

void DealDamage(int DamageValue)
{
    CurrentHealth -= DamageValue; //Deduct the damage dealt from the player's health
    HealthBar = CalculatingHealth();
    if(CurrentHealth <= 0) //If health is 0
    {
        PlayerDead(); //Calling the function
    }
}

void CalculatingHealth()
{
    int healthdecrease =  CurrentHealth / MaxHealth;
}

void PlayerDead()
{
    CurrentHealth = 0; //Currenthealth is 0
    LaserLevelManager.LoadLevel("Lose"); //Take player to the lose scene

   }


}

最佳答案

HealthBar是Slider类型。 CalculatingHealth是一个不返回任何内容的函数(因此无效)。
您尝试设置一个变量初始值,以将Slider类型键入为无效值。这是不可能的。

你可以:

float CalculatingHealth()
{
    return healthdecrease =  CurrentHealth / MaxHealth;
}




HealthBar.value = CalculatingHealth();


注意:https://docs.unity3d.com/ScriptReference/UI.Slider-value.html

关于c# - 当玩家与激光碰撞时,健康栏不会减少,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56118068/

10-09 03:08