Unity3d Toggle onValueChanged 传参数 错误(始终为最后一个实例的值)

代码:

public IEnumerator RefreshFoodInfo()
{
	yield return new WaitForEndOfFrame();
	for (int i = 0; i < foodPanel.transform.childCount; i++)
	{
		GameObject go = foodPanel.transform.GetChild(i).gameObject;
		Destroy(go);
	}

	foreach (var temp in CSJManager.instance.foodManager.foodDic)
	{
		FoodData food = temp.Value;
		GameObject item = Instantiate(Resources.Load("Prefabs/FoodToggle", typeof(GameObject))) as GameObject;
		item.transform.SetParent(foodPanel.transform, false);
		item.name = food.name;
		item.transform.FindChild("TextName").GetComponent().text = food.name;
		item.transform.FindChild("TextIndex").GetComponent().text = food.index.ToString();

		Toggle toggle = item.GetComponent();
		toggle.onValueChanged.AddListener(
			delegate(bool isOn)
			{
				this.OnToggleValueChanged(isOn, item);
			}
		);

		toggle.group = foodPanel.GetComponent();
		curFood = null;
	}
	
	buttonAdd.SetActive(true);
	buttonUpdate.SetActive(false);
	buttonDelete.SetActive(false);
}

public void OnToggleValueChanged(bool isOn, GameObject obj)
{
	if (isOn)
	{
		curFood = obj;
		inputFieldIndex.text = obj.transform.FindChild("TextIndex").GetComponent().text;
		inputFieldName.text = obj.transform.FindChild("TextName").GetComponent().text;
		buttonAdd.SetActive(false);
		buttonUpdate.SetActive(true);
		buttonDelete.SetActive(true);
	}    
}

obj始终为最后一个实例的obj。

错误原因:函数返回值为IEnumerator。   RefreshFoodInfo() 不能为协程函数。

你可能感兴趣的:(Unity3D)