繁体   English   中英

如何最小化else if语句的使用?

[英]how do i minimise the use of else if statements?

如何设置方向值而不必抛出其他所有选项?

if (Input.GetKey(right_button)) { direction = 1; }
else if(Input.GetKey(left_button)) { direction = -1; }        
else { direction = 0; }
if (direction!=0) { rb.velocity = new Vector2(player_speed*direction, rb.velocity.y);  }

我需要将玩家的输入转化为运动。 我无法使用轴,因为无法像使用此方法一样容易地对其进行修改。

我如何优化这段代码?

没有if / else的另一种写上面的方法是:

direction = Input.GetKey(right_button) 
                ? 1
                : Input.GetKey(left_button)
                      ? -1 
                      : 0;

我不知道这是否更具可读性。 在这种情况下,我认为这比起确定的可读性而言,更偏向于如何编写这段代码。 换句话说,我认为if / else语句不可读-作为轻微的修改,我建议您将正文放在另一行而不是同一行中-但这又是个人喜好:)。

if (Input.GetKey(right_button)) 
{ 
    direction = 1; 
}
else if(Input.GetKey(left_button)) 
{ 
    direction = -1; 
}
else 
{ 
    direction = 0; 
}

关于第二个问题,您的代码中没有任何性能问题。

另一种方法是:

// set the value of 0 to direction from the start and change it if it is needed
direction = 0;
if (Input.GetKey(right_button)) 
{ 
    direction = 1; 
}
if(Input.GetKey(left_button)) 
{ 
    direction = -1; 
}

本质上,我们从一开始就将direction的值设置为0,并且仅在需要时才将其重新设置( Input.GetKey(right_button)Input.GetKey(left_button)返回true)。

您担心优化还为时过早。 就性能而言,@ Christos的答案是最好的(复制如下)

// set the value of 0 to direction from the start and change it if it is needed
direction = 0;
if (Input.GetKey(right_button)) 
{ 
    direction = 1; 
}
if(Input.GetKey(left_button)) 
{ 
    direction = -1; 
}

这是唯一的优化,因为它从代码路径中删除了一个分支。

我会说,出于样式和可读性的考虑,请远离三元运算符(使用bool?1:0语法)。 对于返回明确条件的清晰可读值之外的所有内容,它们通常会导致代码更加混乱。

在这些不同的实现方式中要考虑的事情是,您是否希望角色仅移动四个方向(假设您可以上下叠加)或支持对角线移动。 删除代码中的“ else”语句将使之成为对角线。 如果您保留“ else if”,那么您将只能沿基本方向移动。 如果您只想左右移动,则要考虑一下当两者都按下时会发生什么。 玩家不走哪儿吗? 玩家是否朝着最后按下的方向移动? 如果加起来,如果按下3个按钮,如何跟踪?

您可以定义一个集合,该集合确定哪些输入提供哪个方向:

var directionMap = new List<(bool isInputPressed, int directionalValue)>
{
    (Input.GetKey(right_button), 1),
    (Input.GetKey(left_button), -1)
};

然后要获取方向,只需从集合中isInputPressed为true的记录中获取directionalValue

var direction = directionMap.Where(x => x.isInputPressed).Sum(x => x.directionalValue);

如果以某种方式同时按下两个按钮,则在此处使用.Where()可能会产生意外的结果。 如果从未发生过这种情况,则可以将以上内容改为使用.SingleOrDefault()

var direction = directionMap.SingleOrDefault(x => x.isInputPressed).directionalValue;

请注意,如果一次按下多个按钮,将产生异常。 您可以在try / catch块中处理此异常。 或者,您可以在调用.SingleOrDefault()之前验证是否仅按下了一个,然后进行相应的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM