using UnityEngine;
using UnityEngine.UI;
public class HealthBarController : MonoBehaviour
{
private GameObject[] heartContainers;
private Image[] heartFills;
public Transform heartsParent;
public GameObject heartContainerPrefab;
private void Start()
{
// Should I use lists? Maybe :)
heartContainers = new GameObject[(int)PlayerStats.Instance.MaxTotalHealth];
heartFills = new Image[(int)PlayerStats.Instance.MaxTotalHealth];
PlayerStats.Instance.onHealthChangedCallback += UpdateHeartsHUD;
InstantiateHeartContainers();
UpdateHeartsHUD();
}
public void UpdateHeartsHUD()
{
SetHeartContainers();
SetFilledHearts();
}
void SetHeartContainers()
{
for (int i = 0; i < heartContainers.Length; i++)
{
if (i < PlayerStats.Instance.MaxHealth)
{
heartContainers[i].SetActive(true);
}
else
{
heartContainers[i].SetActive(false);
}
}
}
void SetFilledHearts()
{
for (int i = 0; i < heartFills.Length; i++)
{
if (i < PlayerStats.Instance.Health)
{
heartFills[i].fillAmount = 1;
}
else
{
heartFills[i].fillAmount = 0;
}
}
if (PlayerStats.Instance.Health % 1 != 0)
{
int lastPos = Mathf.FloorToInt(PlayerStats.Instance.Health);
heartFills[lastPos].fillAmount = PlayerStats.Instance.Health % 1;
}
}
void InstantiateHeartContainers()
{
for (int i = 0; i < PlayerStats.Instance.MaxTotalHealth; i++)
{
GameObject temp = Instantiate(heartContainerPrefab);
temp.transform.SetParent(heartsParent, false);
heartContainers[i] = temp;
heartFills[i] = temp.transform.Find("HeartFill").GetComponent<Image>();
}
}
}
这是HealthbarController
,当损坏为按钮时起作用。与heal
和addheart
相同,但我无法让敌人造成伤害。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageScript : MonoBehaviour
{
public void Hurt(float dmg)
{
PlayerStats.Instance.TakeDamage(dmg);
}
}
这是我敌人的伤害脚本。与玩家碰撞时,如何使敌人对玩家造成伤害?我尝试使用OnCollisionEnter
,但是每当我将其放入代码中时,我只会遇到很多错误。
答案 0 :(得分:0)
如果您尝试给敌人加上标签“敌人”,并给玩家一个球体碰撞器(已选中isTrigger),该怎么办?
然后制作一个破坏脚本,例如:
public class takeDamage : MonoBehaviour
{
private int PlayerHp = 10f;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag( "Enemy")) {
PlayerHp -= 1;
Debug.Log("Hit, HP: " + PlayerHp);
//Add GUI update function here
}
}
}
并将其附加到播放器上。
别忘了将球体碰撞器缩放到适当的大小。