这是一段unity自定义按钮的代码请给出注释并优化它public class MyBtn public bool isPressing = false; public bool onPressed = false; public bool onReleasd = false; bool curState = false; bool lastState = false;
// MyBtn类,用于自定义按钮 public class MyBtn { // 当前按钮是否被按下 public bool isPressing = false;
// 按钮是否被按下
public bool onPressed = false;
// 按钮是否被释放
public bool onReleased = false;
// 当前状态
bool curState = false;
// 上一次状态
bool lastState = false;
// 每帧调用的方法,传入input表示按钮是否被按下
public void Tick(bool input)
{
// 更新当前状态
curState = input;
// 更新isPressing状态
isPressing = curState;
// 重置onPressed和onReleased状态
onPressed = false;
onReleased = false;
// 判断当前状态和上一次状态是否不同
if (curState != lastState)
{
// 如果当前状态为按下状态
if (curState)
{
// 将onPressed状态设置为true
onPressed = true;
}
else // 当前状态为释放状态
{
// 将onReleased状态设置为true
onReleased = true;
}
}
// 更新上一次状态
lastState = curState;
}
}
// 优化后的代码 public class MyBtn { public bool IsPressing { get; private set; } public bool IsPressed { get; private set; } public bool IsReleased { get; private set; }
private bool _lastState;
public void Tick(bool input)
{
IsPressed = false;
IsReleased = false;
if (input != _lastState)
{
if (input)
{
IsPressed = true;
}
else
{
IsReleased = true;
}
}
IsPressing = input;
_lastState = input;
}
}
// 优化说明: // 1. 将变量名改为驼峰式,符合C#命名规范 // 2. 通过属性取代公共字段,保护变量的可访问性 // 3. 简化代码逻辑,去除无用变量,减少代码量
原文地址: https://www.cveoy.top/t/topic/0ji 著作权归作者所有。请勿转载和采集!