网格碰撞器按钮一次检测到 60 次点击:(

问题描述 投票:0回答:1

我正在制作一款游戏,使用一堆不同的抽象形状作为地图的省份。我附加了网格碰撞器以及脚本来检测何时单击网格。它应该打印到控制台一次,但打印了 62 次。我尝试了很多不同的编写脚本的方法,但没有任何效果,请帮忙!

这是我的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpaceButton : MonoBehaviour
{
    private Camera mainCamera;

    void Start()
    {
        // Get reference to the main camera
        mainCamera = Camera.main;
    }

    void Update()
    {
        // Check for mouse click
        if (Input.GetMouseButtonDown(0))
        {
            // Cast a ray from the mouse position into the scene
            Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;

            // Check if the ray hits a collider with a MeshCollider attached
            if (Physics.Raycast(ray, out hitInfo) && hitInfo.collider is MeshCollider)
            {
                // Print the name of the GameObject that was clicked
                Debug.Log("Clicked on GameObject: " + hitInfo.collider.gameObject.name);

                // You can add additional code here to perform actions when the GameObject is clicked
            }
        }
    }
}

我的输出是预期的,只比需要的多了 60 倍。

c# unity-game-engine
1个回答
0
投票

因为你的游戏似乎以 62 FPS 运行。

为了避免多次点击,您需要类似的东西:

private bool clickDetected = false;

[...]

if (Physics.Raycast(ray, out hitInfo) && hitInfo.collider is MeshCollider){
   Debug.Log("Clicked on GameObject: " + hitInfo.collider.gameObject.name);

   clickDetected = true;
}
© www.soinside.com 2019 - 2024. All rights reserved.