统一3D |无法将运行状况栏画布对象拖动到游戏对象运行状况栏参考中



我创建了一个对象"健康酒吧;进入我的画布,并将我的HealthBar脚本附加到画布上:

HealthBar检查员

现在我想把这个健康条引用到我正在生成的怪物中,但它不允许我把它插入公共引用中:

对象中的引用不接受HealthBar

这是我的HealthBar脚本的代码:

public Slider slider;
public void SetMaxHealth(int health)
{
slider.maxValue = health;
slider.value = health;
}
public void SetHealth(int health)
{
slider.value = health;
}

这是我的MonsterManager的代码:

public int maxHealth = 100;
public int currentHealth;
public HealthBar healthBar;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
healthBar = GameObject.FindObjectOfType<HealthBar>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
TakeDamage(20);
}

}
void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}

当你说你正在生成一个怪物时,我认为你的意思是你正在将一个怪物实例化到你的场景中。

前言在大多数情况下不接受对场景项的引用。这是有道理的,但为了简单起见,让我们把它当作真的。

考虑到这一点,解决问题的最懒惰的方法是在怪物出生时找到健康栏。

private HealthBar healthBar;
void Start()
{
healthBar = GameObject.Find("Canvas/HealthBar");
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
healthBar = GameObject.FindObjectOfType<HealthBar>();
}

虽然这对你来说应该有效,但最好找到一次健康栏并缓存引用。你可以在游戏管理器中这样做,所以当你的怪物运行它的Start方法时,它可以简单地从游戏管理器获得参考。

不能将场景变量分配给预制件。您可以在怪物预制中放置画布,并将其渲染模式设置为"世界"。然后,当实例化怪物时,必须将画布的摄影机变量指定给游戏摄影机。我建议你读一下:

根据我的经验,许多世界空间画布比一个不断被弄脏的大覆盖层更快。

因此,使用多个世界画布似乎是一个不错的解决方案。

最新更新