给出以下层次结构:
- Canvas
- Toggle 1
- Toggle 2
- Toggle 3
其中切换有一个共同的ToggleGroup,最初只选择了一个Toggle,并且以下脚本附加到Canvas:
public class Testscript : MonoBehaviour {
void Start () {
StartCoroutine (LateStart ());
}
IEnumerator LateStart() {
yield return new WaitForEndOfFrame ();
var toggles = GetComponentsInChildren<Toggle> ();
foreach (Toggle toggle in toggles) {
var captured = toggle;
captured.onValueChanged.AddListener (b => {
Debug.Log (captured.name + " changed to " + b);
});
}
}
}
无论我选择什么切换,输出都是:
Toggle 3 changed to False
Toggle 3 changed to True
但是如果我在这样的函数中创建UnityAction<bool>
:
public class Testscript : MonoBehaviour {
void Start () {
StartCoroutine (LateStart ());
}
IEnumerator LateStart() {
yield return new WaitForEndOfFrame ();
var toggles = GetComponentsInChildren<Toggle> ();
foreach (Toggle toggle in toggles) {
var captured = toggle;
captured.onValueChanged.AddListener (makeListener(captured));
}
}
private UnityAction<bool> makeListener(Toggle toggle) {
return b => {
Debug.Log (toggle.name + " changed to " + b);
};
}
}
我得到了预期的结果:
Toggle 1 changed to False
Toggle 2 changed to True
这里发生了什么?为什么这个在Coroutine中不起作用?
还值得注意的是,如果我导出并作为UWP App而不是独立的Build运行,第一个示例 按预期工作,所以我怀疑这种行为是由实现引起的细节我不知道。