如何使 OnControllerColliderHit 方法只检测一次碰撞?

How to make OnControllerColliderHit method to detect collision only once?

OnControllerColliderHit 方法检测每一帧的碰撞。当我用对撞机触摸另一个物体时,我希望它 只被调用一次

这是我现在拥有的示例。看看下面的碰撞计数器:https://youtu.be/-2t45tkWTc8

我希望 OnControllerColliderHit 方法类似于 OnCollisionEnter.

我的 CollisionDetection 脚本:

public class SphereCollisionHandler : MonoBehaviour
{
    
    private int collisionCounter;

    [SerializeField] private GameObject gameObj;
    private TMP_Text textMesh;

    void Start ()
    {
        textMesh = gameObj.GetComponent<TMP_Text>();
    }

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        if (hit.gameObject.tag == "Cube")
        {
            collisionCounter = collisionCounter + 1;
            textMesh.text = collisionCounter.ToString();
        }
    }
}

我已经尝试过使用 OnCollisionEnter,但它对具有 CharacterController 的 Player Object 效果不佳。

API OnControllerColliderHit 确实听起来很有道理,在移动时调用每一帧。

This can be used to push objects when they collide with the character.


想要获得一共只获得一次只需加个flag

private bool alreadyHit;

然后

void OnControllerColliderHit(ControllerColliderHit hit)
{
    if(alreadyHit) return;

    if (hit.gameObject.CompareTag("Cube"))
    {
        alreadyHit = true;

        collisionCounter = collisionCounter + 1;
        textMesh.text = collisionCounter.ToString();
    }
}

或者,如果您的目标是跟踪每个对象的每次点击,您可以使用类似

的东西
private readonly HashSet<GameObject> alreadyCollidedWith = new HashSet<GameObject>();

然后

void OnControllerColliderHit(ControllerColliderHit hit)
{
    if (hit.gameObject.CompareTag("Cube") && !alreadyCollidedWith.Contains(hit.gameObject))
    {
        alreadyCollidedWith.Add(hit.gameObject);

        collisionCounter = collisionCounter + 1;
        textMesh.text = collisionCounter.ToString();
    }
}