【发布时间】:2021-05-12 19:57:41
【问题描述】:
在我的游戏中,我有一个有生命值的玩家,我目前正在尝试添加一个生命值条,但我的一个问题是当我的玩家失去生命值时,我的生命值条不会改变。在我的脚本中,更新健康栏的脚本链接到我的健康脚本,但是当我的玩家失去 hp 时,玩家的 hp 在健康栏中不会改变,我不确定为什么。我知道玩家确实会失去 hp,所以问题是即使脚本被链接,hp 在单独的脚本上也不会改变。我的健康栏的脚本:
抱歉,如果代码不好,我是一个菜鸟程序员。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthBArScript : Health
{
private void Update()
{
transform.localScale = new Vector3(healthPoints / 100, 1.0f, 1.0f);
}
}
如果有必要,我的健康脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Health : MonoBehaviour
{
public float healthPoints = 100.0f;
private Coroutine onHit = null;
private void Update()
{
StartCoroutine(Updaate());
}
IEnumerator Updaate()
{
if (healthPoints <= 0)
{
Destroy(gameObject);
}
if (healthPoints >= 101.0f)
{
healthPoints = 100.0f;
}
yield return new WaitForSeconds(2.0f);
}
private void OnTriggerEnter(Collider coll)
{
if (coll.gameObject.tag == "Zombie")
{
if (onHit == null)
onHit = StartCoroutine(HitDelay());
}
if(coll.gameObject.tag == "Health")
{
healthPoints = healthPoints + 10;
}
if (coll.gameObject.tag == "Health_1")
{
healthPoints = 100.0f;
}
}
IEnumerator HitDelay()
{
healthPoints = healthPoints - 25;
yield return new WaitForSeconds(2.0f);
onHit = null;
}
}
【问题讨论】:
-
那么健康栏脚本在健康栏上?健康栏如何知道玩家的健康状况?我想你可能混淆了继承和引用。
-
@hijinxbassist 我相信这是继承,但我不确定。我不记得它到底是什么,但我能解释它的最好方法是我使用
Health而不是MonoBehaviour。我认为这是继承,但我不确定 -
是的,那部分是继承。如果我错了,请纠正我。我假设您在某种 UI 元素上有 HealthBarScript。然后,您的播放器对象上有 Health 脚本。这是正确的吗?
-
@hijinxbassist 是的,这是正确的
-
好的。所以你确实混淆了继承和引用。引用是指某事的特定实例,即。健康。场景中可以有任意数量的 Health 脚本,您需要在播放器对象上引用其中的一个。让我举个简单的例子,1 分钟。
标签: c# visual-studio unity3d variables