我有一个 public Image[]
可以从 Unity Editor 获取场景中存在的许多 Image UI
。
现在我想通过名称从场景中停用其中的一个或多个。
但我无法通过 Images
的字符串名称访问此数组项。只能通过索引的 int 编号访问,如 Images[0]
我之前尝试过 Dictionary
Class 和论坛上的其他解决方案,但找不到方法。
我该怎么做?
最佳答案
对于数组:
使用 for 循环遍历图像数组,然后比较名称。如果它们匹配,则停用它们。
public Image[] image;
void activateImage(string imageName, bool enable)
{
for (int i = 0; i < image.Length; i++)
{
if (image[i].name == imageName)
{
image[i].enabled = enable;//Good for performace
// OR
//image[i].gameObject.SetActive(enable);
}
}
}
用法:
激活
activateImage("nextImage", true);
停用
activateImage("nextImage", false);
字典:
Dictionary<string, Image> image = new Dictionary<string, Image>();
void activateImage(string imageName, bool enable)
{
if (image.ContainsKey(imageName))
{
image[imageName].enabled = enable;//Good for performace
// OR
//image[imageName].gameObject.SetActive(enable);
}
}
将图像添加到词典:
public Image myImage;
image.Add(myImage.name, myImage);
或
image.Add("myImageName", myImage);
关于c# - 在 Unity 中按字符串名称访问数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39613885/