C# 敌人的生命棒和承受伤害
我已将以下脚本添加到我的敌人中,以获得健康栏:C# 敌人的生命棒和承受伤害,c#,unity3d,C#,Unity3d,我已将以下脚本添加到我的敌人中,以获得健康栏: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Enemy_Health : MonoBehaviour { public float health; public float maxHealth; public GameObject hea
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Enemy_Health : MonoBehaviour {
public float health;
public float maxHealth;
public GameObject healthBarUI;
public Slider slider;
private void Start()
{
health = maxHealth;
slider.value = calculateHealth();
}
private void Update()
{
slider.value = calculateHealth();
if (health < maxHealth)
{
healthBarUI.SetActive(true);
}
if (health <= 0)
{
Destroy(gameObject);
}
if (health > maxHealth)
{
health = maxHealth;
}
}
float calculateHealth()
{
return health / maxHealth;
}
}
使用系统集合;
使用System.Collections.Generic;
使用UnityEngine;
使用UnityEngine.UI;
公共卫生:单一行为{
公共卫生;
公共卫生;
公共游戏对象healthBarUI;
公共滑块;
私有void Start()
{
健康=最大健康;
slider.value=calculateHealth();
}
私有void更新()
{
slider.value=calculateHealth();
如果(健康<最大健康)
{
healthBarUI.SetActive(true);
}
if(健康maxHealth)
{
健康=最大健康;
}
}
浮动计算健康()
{
返回健康/maxHealth;
}
}
它运行良好。但是,我的玩家有一把武器(斧头),我希望当我的玩家使用武器攻击时,敌人的生命值条会减少。添加一个降低敌人攻击时生命值的功能。大概是这样的:
public void DecreaseHealth(healthamount)
{
health -= healthamount;
}
在你的玩家脚本中调用此函数,使用你希望在攻击时减少的确切生命值。我有多个敌人,有多个生命值条,我可以使用你的答案吗?我根据你提供的脚本给出了我的答案。我不知道你的代码结构,但基本概念是一样的,就像这段代码。如果它适合你的结构,那么你可以使用它。@t当你的玩家攻击时,使用
物理
找到他们正在攻击的敌人(如果有的话),并调用GetComponen()
获取对敌人健康脚本的引用。然后,您可以在其上调用DecreaseHealth
。