${}
两个变量都用HP_Bar_Green填充。如何防止这种情况发生?为什么会这样呢?
我尝试附加this.GetComponent();我和我都试图写一个IF语句来防止这种情况的发生,但是没有运气。
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_Red移到EnemyDetection脚本。这样,我可以将其设置为PUBLIC,然后通过脚本将其手动插入Unity inspector。但是,当我按PLAY键时,图像从脚本字段中消失了,但是它仍然出现在屏幕上。然后,当游戏处于播放模式并且脚本运行正常时,我可以将图像放回检查器上的字段中。那么为什么图像不被接受?
if (HP_Bar_Red == HP_Bar_Green)
{
HP_Bar_Red = GetComponent<Image>();
Debug.Log("RED "+HP_Bar_Red);
HP_Bar_Red.gameObject.SetActive(false);
}
答案 0 :(得分: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.
}
}
答案 1 :(得分:0)
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //Make sure that the name fits to the .cs file name and add this script to a GameObejct in the scene public class HPsc : MonoBehaviour { public static Image HP_Bar_Green; public static Image HP_Bar_Red; //Add your images here in the scene - Inspector: public Image imgGreen; public Image imgRed; private void Awake() { HP_Bar_Green = imgRed; //Make them accessable over the static variables HP_Bar_Red = imgGreen; } //Test (also usable in another class): private void Start() { Debug.Log(HPsc.HP_Bar_Red != null); } }