c# - 玩家在与标记对象碰撞时消失

标签 c# unity3d scripting collision

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

在处理好模型和动画之后,我现在正在处理碰撞和计数 UI。

对于碰撞,在我的播放器 Controller 上(我正在使用来自播放器的 ThirdPersonUserController Unity Standard Assets - 它简化了整个动画过程),我添加了以下函数:

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!";
    }
}

但是,像这样,当玩家击中带有“Present”标签的对象时,即使计数正常,玩家也会消失。

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

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

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

我的播放器有一个胶囊碰撞器和一个刚体。

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

任何关于如何让我的玩家留在场景中同时移除其他对象和减少计数的指导都将受到赞赏。

最佳答案

几件事。您正在销毁不正确的游戏对象:

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();
        }
    }

更新为:

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

始终使用针对性能优化的 CompareTag()

设置 Collider IsTrigger 属性将使用 OnTriggerEnter 事件,而不是 OnCollisionEnter

On the first physics update where the collision is detected, the OnCollisionEnter function is called. During updates where contact is maintained, OnCollisionStay is called and finally, OnCollisionExit indicates that contact has been broken. Trigger colliders call the analogous OnTriggerEnter, OnTriggerStay and OnTriggerExit functions.

参见 docs

关于c# - 玩家在与标记对象碰撞时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184990/

相关文章:

c# - Asp.net 从 aspx 中的文本框获取值以隐藏代码

c# - 在存储过程的 SqlParameter 中使用 DateTime,格式错误

c# - 计算阴影的大小

android - 我可以在 Unity Android Free 中使用 Google Play 游戏服务 - 实时多人游戏吗?

unity3d - 为什么Unity在烘焙资源时会卡住?

javascript - 如何通过浏览器检测某个协议(protocol)是否受支持?

c# - 如何在Control上绘图以使绘图不消失?

c# - Json.NET 仅输出 C# 中的值

python - 如何更新 $PATH

linux - 如果 grep 找到匹配项,则打印 grep 关键字