IAb*_*act 2 c# unity-game-engine
我有一个MonoBehavior使用这些方法的源脚本:
private void Update () {
if (Input.GetMouseButton(0)) {
HandleInput();
}
}
private void HandleInput () {
Ray inputRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(inputRay, out hit)) {
var position = transform.InverseTransformPoint(hit.point);
Coordinates coords = Coordinates.FromPosition(position);
HexCell cell = null;
if (!cells.TryGetValue(coords, out cell)) {
var err = string.Format("{0} is an invalid position and coordinates are improperly calculated: {1}", position, coords);
print(err);
throw new System.ArgumentException(err);
}
print(string.Format("[{0}] cell: [{1}] {2}", DateTime.Now, cell.id, cell.coordinates));
OnCellTouched(cell);
}
}
Run Code Online (Sandbox Code Playgroud)
网格是透明的,我按预期得到六边形(单元格).在编辑器中,当我单击一个单元格时,我得到一条消息输出:
[05.31.2017.14.15.14.2836] cell: [0] [x=0;y=0;z=0]
[05.31.2017.14.15.15.7359] cell: [197] [x=12;y=-22;z=10]
Run Code Online (Sandbox Code Playgroud)
但是,当我构建并运行应用程序时:单击任何单元格,每次单击记录以下4 - 6次:
[05.31.2017.14.57.50.1588] cell: [0] [x=0;y=0;z=0]
[05.31.2017.14.57.50.1695] cell: [0] [x=0;y=0;z=0]
[05.31.2017.14.57.50.1861] cell: [0] [x=0;y=0;z=0]
[05.31.2017.14.57.50.2028] cell: [0] [x=0;y=0;z=0]
[05.31.2017.14.57.50.2195] cell: [0] [x=0;y=0;z=0]
[05.31.2017.14.57.52.6195] cell: [197] [x=12;y=-22;z=10]
[05.31.2017.14.57.52.6360] cell: [197] [x=12;y=-22;z=10]
[05.31.2017.14.57.52.6530] cell: [197] [x=12;y=-22;z=10]
[05.31.2017.14.57.52.6691] cell: [197] [x=12;y=-22;z=10]
[05.31.2017.14.57.52.6857] cell: [197] [x=12;y=-22;z=10]
Run Code Online (Sandbox Code Playgroud)
编辑器忽略的Unity引擎是否可能多次传播单击?由于每个日志条目具有不同的时间戳(毫秒),因此范围差异为157-170ms.
Unity范式中是否存在"最佳实践"?处理程序应该是异步的吗?处理程序是否应忽略某个窗口中的后续调用?
当我想在六边形瓷砖上使用单击作为切换时,这似乎会导致问题.
几乎所有新的Unity程序员都会遇到这个问题.
Input.GetMouseButton是true按住鼠标按钮直到释放的每一帧.同样,它将在true 每个帧发布之前.
Input.GetMouseButtonDown是true仅仅一次,当按住鼠标按钮.这会不会是true直到鼠标被释放并再次按下一次.
在你的情况下,它看起来像你需要的Input.GetMouseButtonDown 只有真实一次,并且只有在释放并再次按下时才能再次为真.
同样的事情适用于GetKey,GetKeyDown和GetKeyUp.
注意:
如果您使用Input.GetMouseButtonDown但仍然多次调用它,请确保您的脚本未附加到另一个或多个GameObjects.