如何提取重复的 button 事件方法
时间:2020-07-13 23:10:08
收藏:0
阅读:58
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
};
}
原文:https://www.cnblogs.com/forhot2000/p/13296287.html
评论(0)