我有一個按鈕預製,所以我試圖將一個場景對象腳本關聯到它,我想這是不可能的,但現在我試圖將按鈕點擊動作與某些腳本中的動態創建的按鈕相關聯,這裏是代碼片段。Unity3d將一個動作與一個不同的參數(增加索引)關聯到一個按鈕預製
int index = 0
public IEnumerator GenerateItems()
{
foreach (ArrayList eat in eatArray))
{
Debug.Log (index);
GameObject localItem = (GameObject)Instantiate(item, Vector3.zero, Quaternion.identity);
UnityEngine.Events.UnityAction action =() => { Debug.Log(index); };
++index;
localItem.GetComponent<Button>().onClick.AddListener(action);
localItem.transform.SetParent(grid.transform);
localItem.transform.localScale = autoLocalScale;
localItem.transform.localPosition = Vector3.zero;
}
yield return new WaitForSeconds(.1f);
///1. Two ways to move the scroll to first item
scrollRect.horizontalNormalizedPosition = 0;
// //2. Moving the scroll bar to left
// //scrollBar.value = 0;
}
我所得到的指數值是2,我想,當我對索引按鈕點擊(如2個按鈕有那麼我應該在第一按鈕得到0點擊和1對第二鈕點擊) 。
該項目是一個預製,包含一個按鈕組件,我可以通過獲取組件功能並向該按鈕添加操作.eatArray也是一個arrayList。我instantitate的項目localItem給它的位置,因此localItem是與它的組件按鈕一個遊戲對象.eatarray基本上是用來獲取的次數累計數的循環運行
編輯:
public void OnClick()
{
Debug.Log(index);
}
當我附上按鈕預製在它的指數變量的劇本,我增加了指數在for循環
localItem.GetComponent<GridButton>().index = index++;
我能得到正確的索引值,現在這個的OnClick()函數返回正確的索引,但因爲我不能這樣做se有很多函數寫在其他腳本上,我不想複製代碼並且不能使用引用,因爲許多函數都是私有的。
因此,當您點擊腳本中的按鈕時,您會得到什麼索引或錯誤索引或固定數量或什麼也沒有或錯誤或..? –
我得到2表示在循環結束時可用的索引值,第一個Debug.Log(索引)產生0和1,但不會與操作關聯,而是循環結束處的索引與每個按鈕點擊 –
此帖很難閱讀。所以'item' gameobject有一個連接到它的按鈕,它將被實例化? 'localItem.GetComponent