Unity输入在印刷机中多次检测到

我有一个使用这些方法的源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); } } 

网格是透明的,我按预期得到六边形(单元格)。 在编辑器中,当我单击一个单元格时,我得到一条消息输出:

 [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] 

但是,当我构建并运行应用程序时:单击任何单元格,每次单击记录以下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] 

是否可能由编辑忽略的Unity引擎多次传播单击? 由于每个日志条目具有不同的时间戳(毫秒),因此范围差异为157-170ms。

Unity范式中是否存在“最佳实践”? 处理程序应该是异步的吗? 处理程序是否应该忽略某个窗口中的后续调用?

当我想在六边形瓷砖上使用单击作为切换时,这似乎会导致问题。

几乎所有新的Unity程序员都会遇到这个问题。

  • Input.GetMouseButton鼠标按钮直到释放时, Input.GetMouseButton为每帧Input.GetMouseButtontrue 。 同样,在每一帧发布之前都是true

  • 当鼠标按钮按住时, Input.GetMouseButtonDown只有一次 。 直到鼠标被释放并再次按下才会再次出现。

在你的情况下,看起来你需要Input.GetMouseButtonDown ,它只会是真一次,并且只有在释放并再次按下时才能再次为真。

同样的事情适用于GetKeyGetKeyDownGetKeyUp

注意

如果您使用Input.GetMouseButtonDown但仍然多次调用它,请确保您的脚本未附加到另一个或多个GameObjects。

在此处输入图像描述