如何提取重复的 button 事件方法
Unity 中的事件一般都是回调 UnityAction 或者 UnityAction
重构前
void Awake()
{
// ...
walkUpButton.onClick.AddListener(() => {
commandPanel.Walk(Direction.Up);
// some other repeated actions
});
walkRightButton.onClick.AddListener(() => {
commandPanel.Walk(Direction.Right);
// some other repeated actions
});
walkDownButton.onClick.AddListener(() => {
commandPanel.Walk(Direction.Down);
// some other repeated actions
});
walkLeftButton.onClick.AddListener(() => {
commandPanel.Walk(Direction.Left);
// some other repeated actions
});
// ...
}
重构后
void Awake()
{
// ...
walkUpButton.onClick.AddListener(Walk(Direction.Up));
walkRightButton.onClick.AddListener(Walk(Direction.Right));
walkDownButton.onClick.AddListener(Walk(Direction.Down));
walkLeftButton.onClick.AddListener(Walk(Direction.Left));
// ...
}
UnityAction Walk(Direction direction)
{
return () =>
{
commandPanel.Walk(direction);
// some other repeated actions
};
}

浙公网安备 33010602011771号