如何提取重复的 button 事件方法

Unity 中的事件一般都是回调 UnityAction 或者 UnityAction 的,下面示例代码中的几个事件都调用了 commandPanel.Walk(Direction direction) 方法,仅参数不同,可以抽取函数 UnityAction Walk(Direction direction) 来封装这些相同的代码。

重构前

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
    };
}
posted @ 2020-07-13 22:24  forhot2000  阅读(115)  评论(1)    收藏  举报