隐藏健康栏直到敌人在附近 C#

Hiding Health Bar Until Enemy is nearby C#

我知道如何创建碰撞器来检测标记为 "Enemy" 的游戏对象。我也熟悉如何将其设为 isTrigger 事件以及 OnTriggerEnter() 的功能。

我的问题似乎是将图像从我的健康点脚本 (HPsc) 读取到我的 EnemyDetection 脚本中。

在我的 HPsc 中,我已将我的 HP 图像(红色和绿色)声明并分配为 public 静态图像 HP_Green、HP_Red。所以在我的 EnemyDetection 脚本中,我引用了这些 HPsc.HP_Green.SetActive(True) 和 HPsc.HP_Red.SetActive(true)

但是,问题似乎是 SetActive 是针对文本 UI 而不是针对图像的? FadeIn() 和 FadeOut() 真的可以在这里替代吗?

健康栏Class:

public class HPsc
{
    public static Image HP_Bar_Green;
    public static Image HP_Bar_Red; // Allows me to initialize the images in Unity

    void Start()
    {
        HP_Bar_Green = GetComponent<Image>();
        HP_Bar_Red = GetComponent<Image>(); //How I grab the images upon startup
    }
}

敌人检测:

public class EnemyDetection
{
    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Enemy1")
        {
            HpSc.HP_Bar_Green.SetActive(true);
            // This is DetectEnemy trying to grab the image from the other script.
        }
    }
}

***** 解决问题#1 ***** HP_Bar_Green.gameObject.SetActive(真); – 弗雷德里克·维德伯格

只需要将游戏对象串起来!谢谢大家!

****** 问题#2 ****** 好的,现在我的下一个问题是将两个图像都放入正确的变量中。

HP_Bar_Green = transform.GetChild(0).gameObject.GetComponent(); HP_Bar_Red = transform.GetChild(1).gameObject.GetComponent();

我试图确保每个变量只能包含它应该包含的内容。 .GetChild() 看起来很有吸引力,但它引起了很多问题。编译器允许游戏开始运行,但在 5 分钟多的时间里,我在编译器中累积了 20,000 个相同的错误。

***** 问题已解决 *****

哈利路亚!

我将 HP_Bar_Red 移到了我的 EnemyDetection 脚本中。将其设为 public 变量并手动将对象插入到 Unity 检查器中。 (这里有几个人一直在推荐。谢谢大家!祝你们幸福!)

您需要使用

将图像组件上的游戏对象设置为活动或非活动
GameObject.SetActive(boolean)

或者您也可以这样做

HpSc.HP_Bar_Green.enabled = true/false;

Class:

public class EnemyDetection
{
    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Enemy1")
        {
            HpSc.HP_Bar_Green.GameObject.SetActive(true);
            //or
            HpSc.HP_Bar_Green.enabled = true;
            // This is DetectEnemy trying to grab the image from the other script.
        }
    }
}

你可能 运行 对让 HpSc.HP_Bar_Green 保持静态有疑问,所以如果有多个敌人,你可能想要一个 class 来获取 HpSc 组件并将其禁用那个具体的。

public class EnemyDetection
{
    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Enemy1")
        {
            HpSc healthBar = other.GetComponent<HpSc>();

            healthBar.GameObject.SetActive(true);
            //or
            healthBar.enabled = true;
        }
    }
}

非静态变量:

public class HPsc
{
    public Image HP_Bar_Green;
    public Image HP_Bar_Red; // Allows me to initialize the images in Unity

    void Start()
    {
        HP_Bar_Green = this.GetComponent<Image>();
        HP_Bar_Red = this.GetComponent<Image>();
    }
}

因此,您正在尝试对 Image 组件执行 SetActive()。 但是,SetActive()GameObject 到 activate/deactivate 层次结构中的 GameObject 的一部分。

所以你需要先获取GameObject,然后在上面调用SetActive()

myImage.gameObject.SetActive(true);

如果您只想enable/disable Image-您可以做的组件

myImage.enabled = true;