C# Unity,更改数组按钮颜色仅在添加 OnClick.Addlistener 时受影响的最后一个数组
本文关键字:数组 OnClick Addlistener 最后一个 影响 添加 Unity 按钮 颜色 | 更新日期: 2023-09-27 18:25:43
public GameObject SongListParent; // Dragged from the inpsector
private GameObject SongListButton;
private GameObject SongListPrefab
private Object[] myMusic;
void awake(){
for(int i = 0; i < myMusic.Length; i++ ) {
int TempInt = i;
//Instantiate the song list
SongListButtons = (Resources.Load("Prefabs/Button")) as GameObject;
SongListPrefab = (GameObject) Instantiate(SongListButtons);
SongListPrefab.transform.SetParent(SongListParent.transform, false);
//setting the label
datext = SongListPrefab.GetComponentsInChildren<Text>();
datext[0].text = myMusic.name;
//Adding Function and positioning
Vector3 pos = new Vector3(10, i*-30, 0);
SongListPrefab.GetComponent<RectTransform>().localPosition = pos;
GetComponent<AudioSource>().clip = myMusic as AudioClip;
SongListPrefab.GetComponent<Button>().onClick.AddListener(() => lol(TempInt) );
};
}
public void lol(int buttonNo){
//Play Audio Onclick
GetComponent<AudioSource>().clip = myMusic[buttonNo] as AudioClip;
GetComponent<AudioSource>().Play();
//Change Color Onclick, << Problem starts here only the last array gets coloured
Image[] lel = SongListPrefab.GetComponentsInChildren<Image>();
lel[0].color = Color.red;
}
当我运行代码时,只有按钮预制件的最后一个数组在单击时着色,我尝试使用 lel[buttonNo].color 而不是 lel[0].color,但在我单击按钮后,它说数组超出范围。我在这里试图实现的是,当单击按钮时,按钮是彩色的,但是在这种情况下,当我单击任何按钮时,它会为数组中的最后一个按钮着色。任何想法或建议将不胜感激:)
问题就在这里:
Image[] lel = SongListPrefab.GetComponentsInChildren<Image>();
在循环中,将 SongListPrefab
的值重新分配给最后一个实例化的预制件:
SongListPrefab = (GameObject) Instantiate(SongListButtons);
因此,SongListPrefab
将始终是 SongListButtons
中最后一个实例化的游戏对象。
最简单的方法可能是将 Button 传递给lol
函数并像这样更改其颜色:
public void Awake()
{
// previous code
var button = SongListPrefab.GetComponent<Button>();
if (button != null)
button.onClick.AddListener(() => lol(TempInt, button));
}
public void lol(int buttonNo, Button button)
{
//Play Audio Onclick
GetComponent<AudioSource>().clip = myMusic[buttonNo] as AudioClip;
GetComponent<AudioSource>().Play();
//Change Color Onclick, << Problem starts here only the last array gets coloured
button.image.color = Color.red;
}
如果你真的想拥有每个已实例化SongListPrefab
的信息,你应该考虑将所有实例化的GameObject
存储在一个数组或List<GameObject>
中,然后将它们.Add()
到它,然后通过索引访问它lol()
,尽管它以后可能不是防错的。
此外,您可能会考虑仅为按钮行为制作和附加脚本,并将其附加到Inspector
以onClick
是否是一种选择。