我定义了一个切换结构数组。我正在为每个人添加一个监听器。现在我想知道当用户按下切换按钮更改值时哪个切换按钮被更改。我如何从脚本中知道哪个切换已更改并将其用作索引?
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class ToggleData : MonoBehaviour {
[System.Serializable]
public struct toggleInfo {
public Toggle toggle;
public TextMeshProUGUI toggleText;
}
public toggleInfo[] toggles;
public int toggleIndex = 0;
// Start is called before the first frame update
void Start () {
for (int i = 0; i < toggles.Length; i++) {
toggles[i].toggle.onValueChanged.AddListener (delegate {
ToggleValueChanged (toggles[i].toggle);
});
}
}
void ToggleValueChanged (Toggle change) {
Debug.Log ("toggle changed " + toggleIndex); //Get the index here
}
}
最佳答案
你可以例如使用
for (int i = 0; i < toggles.Length; i++)
{
// Due to variable capturing in Linda expresions you have to store
// each value of i in a new variable
// See https://learn.microsoft.com/dotnet/csharp/language-reference/operators/lambda-expressions#capture-of-outer-variables-and-variable-scope-in-lambda-expressions
// and e.g. https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp
var index = i;
toggles[index].toggle.onValueChanged.AddListener (() => ToggleValueChanged (toggles[index].toggle, index));
}
还有
void ToggleValueChanged (Toggle change, int index)
{
Debug.Log ("toggle changed " + index);
}
或者不使用struct
,而是使用class
public class toggleInfo { ... }
并使用
for (int i = 0; i < toggles.Length; i++)
{
// Due to variable capturing in Linda expresions you have to store
// each value of i in a new variable
// See https://learn.microsoft.com/dotnet/csharp/language-reference/operators/lambda-expressions#capture-of-outer-variables-and-variable-scope-in-lambda-expressions
// and e.g. https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp
var index = i;
toggles[index].toggle.onValueChanged.AddListener (() => ToggleValueChanged (toggles[index]));
}
还有
void ToggleValueChanged (toggleInfo info)
{
Debug.Log ("toggle changed " + Array.IndexOf(toggles, info));
}
关于c# - 根据切换数组检查哪个切换已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69225176/