播放器与标记对象碰撞时消失

Gon*_*ica 2 c# scripting collision unity-game-engine

我正在开发一个简单的游戏,其目标是帮助玩家捕捉带有“Present”标签的特定对象。

处理完模型和动画后,我现在正在处理碰撞和计算 UI。

对于碰撞,在我的播放器控制器上(我使用了播放器Unity 标准资产中的 ThirdPersonUserController - 这简化了整个动画过程),我添加了以下功能:

void OnCollisionEnter(Collision other)
{
    if (other.gameObject.tag == "Present")
    {
        Destroy(gameObject);
        count = count - 1;
        SetCountText();
    }
}

void SetCountText()
{
    countText.text = "Count: " + count.ToString();
    if (count == 0)
    {
        winText.text = "Thanks to you the Christmas will be memorable!";
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,像这样,当玩家击中带有“Present”标签的物体时,即使计数正常工作,玩家也会消失。

我试图将 更改OnCollisionEnter为 an OnTriggerEnter,如下所示:

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Present"))
    {
        Destroy(gameObject);
        count = count - 1;
        SetCountText();
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,当玩家点击带有“Present”标签的对象时,它们不会消失。

我的播放器有一个 Capsule Collider 和一个 Rigidbody。

带有“Present”标签的对象有一个 Box Collider 和一个 Rigidbody。

任何有关如何让我的播放器留在场景中同时移除其他对象和减少计数的指导表示赞赏。

Sam*_*l G 5

几样东西。您正在销毁不正确的游戏对象:

void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Present")
        {
            Destroy(gameObject); // this is destroying the current gameobject i.e. the player
            count = count - 1;
            SetCountText();
        }
    }
Run Code Online (Sandbox Code Playgroud)

更新至:

void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.CompareTag("Present"))
        {
            Destroy(other.gameObject); // this is destroying the other gameobject
            count = count - 1;
            SetCountText();
        }
    }
Run Code Online (Sandbox Code Playgroud)

始终使用CompareTag()针对性能进行了优化。

IsTrigger然后设置 Collider属性将使用OnTriggerEnter事件而不是OnCollisionEnter不再使用。

在检测到碰撞的第一次物理更新时,将调用 OnCollisionEnter 函数。在保持联系的更新期间,会调用 OnCollisionStay,最后,OnCollisionExit 指示联系已中断。触发器碰撞器调用类似的 OnTriggerEnter、OnTriggerStay 和 OnTriggerExit 函数。

查看文档