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);
}
}