UnityAction在检视面板中的SerializeField

3

我有一个包含以下内容的脚本:

[SerializeField]
private List<UnityAction> m_method = new List<UnityAction>();
private List<Button> m_button = new List<Button>();

void Start()
{
    //init m_button 
}


// this function is called when the player click on an object in game
void onClick()
{
    for(int i=0; i<m_button.Count; i++)
        m_button[i].AddListener(m_method[i]);
}

我希望在检视面板中定义unityAction,但是没有任何东西显示在检视面板中...

我原以为这会像按钮组件一样:

enter image description here

是否有一种方法可以将操作与序列化字段中的按钮绑定?

1个回答

7
您需要的不是UnityAction,而是UnityEvent,后者可以被序列化到检查器(inspector)中。
UnityForums中,这种区别有详细的解释。

UnityAction is like:

 public delegate void UnityAction();

And UnityEvent is just another way to handle events with the (great) possibility to be serialized so as to be used in the Editor (Inspector) in contrary to plain C# events. A simple example is the onClick event of a Button.

如果您想将UnityEvent传递给AddListener方法,可以使用类似于以下的lambda表达式:

btn.onClick.AddListener(() => unityEvent?.Invoke());

注意"?"以避免调用空动作!

是的,我尝试过UnityEvent,但是AddListener函数不接受UnityEvent...那么如果我有UnityEvent,我该如何将UnityEvent绑定到按钮上呢? - lufydad
1
@lufydad 我已经更新了答案,一种方法是:btn.onClick.AddListener(() => unityEvent?.Invoke()); - Lotan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接