You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity3D物体触发重复碰撞问题求助(本应仅触发一次)

碰撞触发两次的问题排查

我的物体在本应仅触发一次碰撞的场景下,触发了两次碰撞。以下是我的代码:

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

public class DetectCollision : MonoBehaviour {
    int score, nbLives, nbCoinsCollectedPerLevel;

    // Start is called before the first frame update
    void Start() {
        nbCoinsCollectedPerLevel = 0;
    }

    // Update is called once per frame
    void Update() {
    }

    void OnCollisionEnter2D(Collision2D coll) {
        string tagName = coll.collider.gameObject.tag;

        if (tagName == "pick_me") {
            Destroy(coll.collider.gameObject);
            //score++;
            score = PlayerPrefs.GetInt("score");
            score++;
            PlayerPrefs.SetInt("score", score);

            nbCoinsCollectedPerLevel++;

            if (SceneManager.GetActiveScene().name == "level1" && nbCoinsCollectedPerLevel >= 5) {
                SceneManager.LoadScene("level2");
            }
            print("score" + score);
        }

        if (tagName == "avoid_me" || tagName == "reStarter") {
            Destroy(coll.collider.gameObject);
            nbLives = PlayerPrefs.GetInt("nbLives");
            nbLives--;
            PlayerPrefs.SetInt("nbLives", nbLives);
            if (nbLives >= 0)
                SceneManager.LoadScene(SceneManager.GetActiveScene().name);
            else SceneManager.LoadScene("lose");
            print("lives" + nbLives);
        }
    }

    void OnCollisionExit(Collision collisionInfo) {
        print("Collision Out: " + gameObject.name);

        if (tagName == "endOfLevelTwo") {
            SceneManager.LoadScene("win");
        }
    }
}

我尝试排查问题,添加了如下代码:

void OnCollisionExit(Collision collisionInfo) {
    print("Collision Out: " + gameObject.name);
}

但该方法没有起到任何作用。

内容的提问来源于stack exchange,提问作者Neo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 07:45:51