在制作鼠标点击控制人物移动时,我写了如下代码:
public class MouseManager : MonoBehaviour
{
RaycastHit hitinfo;
public event Action<Vector3> MouseEventClickGround;
public event Action<GameObject> MouseEventClickEnemy;
// Update is called once per frame
void Update()
{
MouseControl();
SetCursorTexture();
}
void SetCursorTexture()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitinfo) )
{
//...
}
if (hitinfo.collider == null)
{
Debug.Log("hitNothing");
}
}
void MouseControl()
{
var isMouseClick = Input.GetMouseButtonDown(0);
if (isMouseClick)
{
Debug.Log("Hit mouse");
}
if (isMouseClick && hitinfo.collider != null)
{
Debug.Log("Valid Click");
if (hitinfo.collider.gameObject.CompareTag("Ground"))
{
MouseEventClickGround?.Invoke(hitinfo.point);
}
}
}
}
通过 Raycast
的方式判断鼠标的点击。但是发现使用过程中,存在点击鼠标,有“Hit mouse” 但是没有"Valid Click"的情况 (偶发)。同时鼠标放置在地面上不断产生"hitNothing"。
检查发现collider等都设置正确,如果设置不正确也不可能是偶发事件。最后发现使用物理模块应该在FixUpdate中而不是Update中,改为:
private void FixedUpdate()
{
SetCursorTexture();
}