[英]Can't make collision between enemy and player do damage to the player
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>();
}
}
}
This is the HealthbarController
and it works when the damage is a button.这是
HealthbarController
,它在损坏是一个按钮时起作用。 Same with heal
and addheart
but I can't make my enemies do the damage.与
heal
addheart
相同,但我不能让我的敌人造成伤害。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageScript : MonoBehaviour
{
public void Hurt(float dmg)
{
PlayerStats.Instance.TakeDamage(dmg);
}
}
and this is the damage script for my enemies.这是我的敌人的伤害脚本。 How can I make enemy do damage to the player when colliding with the player?
如何让敌人在与玩家碰撞时对玩家造成伤害? I tried with
OnCollisionEnter
but whenever I put it into the code I only got a bunch of errors.我尝试使用
OnCollisionEnter
但每当我将它放入代码时,我只会遇到一堆错误。
What if you tried giving your enemy the tag "Enemy" and your player a sphere collider (isTrigger checked).如果你尝试给你的敌人一个标签“敌人”和你的玩家一个球体碰撞器(isTrigger 检查)怎么办。
And then make a take damage script for example:然后制作一个承受伤害脚本,例如:
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
}
}
}
and attach it to the player.并将其附加到播放器上。
Don't forget to scale the sphere collider to the appropriate size.不要忘记将球体碰撞器缩放到适当的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.