我在反射问题中挣扎,实际上我不确定这是否是反射问题,但情况如下所示。
public Image IMG1;
int x = 1;
string temp;
temp = "IMG" + x.ToString(); //Now temp is a string with value "IMG1"
在图像类中,我们有可以称呼的"精灵" propet。是否可以使用" temp.sprite"而不是" img1.sprite"?
public Sprite newSprite;
IMG1.sprite = newSprite;
更改为
temp.sprite = newSprite;
非常感谢。
我不确定您是否需要在情况下使用反射。但是我建议尝试使用字典。因此,在开始时,您需要将所有图像字段添加到字典中:
Dictionary<string, Image> dict = new Dictionary<string, Image>();
dict.Add(nameof(IMG1), IMG1);
然后您可以通过:
访问您的字段dict[temp].sprite = xxxx
在性能方面,这种方法要好得多。但是,如果您真的需要通过反射进行操作,则可以查看"动态"关键字,如果您不熟悉反射,可以简化使用反射。
或通过常规反射您可以尝试这样的事情:
FieldInfo fieldInfo = typeof(YourClassWithImageField).GetField(temp);
Image img = fieldInfo.GetValue(ObjectWithYourField) as Image;
if (img != null)
{
img.sprite = xxxx;
}
希望它有帮助。