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

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

两个变量都用 HP_Bar_Green 填充。我怎样才能防止这种情况发生?还有为什么会这样?

我试过附加 this.GetComponent(); 对两者,我试图写一个 IF 语句来防止这种情况发生,但没有运气。

if (HP_Bar_Red == HP_Bar_Green)
{
    HP_Bar_Red = GetComponent<Image>();

    Debug.Log("RED "+HP_Bar_Red);
    HP_Bar_Red.gameObject.SetActive(false);
}

感谢所有帮助和建议!我真的被困在这里了!

**** 更新 ****

我决定将 HP_Bar_Red 移至 EnemyDetection 脚本。这样我就可以将其设为 PUBLIC 并通过脚本手动将其插入 Unity 检查器。但是,当我按下 PLAY 时,图像从脚本字段中消失了,但它仍然出现在屏幕上。然后我可以在游戏处于播放模式并且脚本运行良好时将图像放回检查器的字段中。那么为什么图像不被接受?

public class EnemyDetection : MonoBehaviour
{
    public Image HP_Bar_Red;

    private void Start()
    {

        HP_Bar_Red = GetComponent<Image>();
        Debug.Log("RED " + HP_Bar_Red);

        // HP_Bar_Red.gameObject.SetActive(false);
        HP_Bar_Red.gameObject.SetActive(false);
    }
}
4

2 回答 2

1

你有多个Image组件连接gameObject正确吗?

如果是这种情况,您需要使用GetComponets<T>()并使用返回的Component[]

public class HPsc
{    
    private Component[] _images;

    void Start()
    {
        Images = GetComponents<Image>();
    }

    void Update()
    {
        // Assuming the order is correct, you could also make some sort of 
        // id property to search the array with.
        var green = images[0];
        var red = images[1];

        // Do something with the images.
    }
}
于 2018-08-24T17:03:17.160 回答
0
    使用 System.Collections;
    使用 System.Collections.Generic;
    使用 UnityEngine;
    使用 UnityEngine.UI;

    //确保名称适合.cs文件名并将此脚本添加到场景中的GameObejct
    公共类 HPsc : MonoBehaviour
    {
        公共静态图像 HP_Bar_Green;
        公共静态图像 HP_Bar_Red;

        //在场景中添加您的图像 - 检查器:
        公众形象 imgGreen;
        公共图像 imgRed;

        私人无效唤醒()
        {
            HP_Bar_Green = imgRed; //使它们可以通过静态变量访问
            HP_Bar_Red = imgGreen;
        }

        //测试(也可以在另一个类中使用):
        私人无效开始()
        {
            Debug.Log(HPsc.HP_Bar_Red != null);
        }
    }

于 2018-08-24T23:29:27.467 回答