首页 > 解决方案 > 如果 Else 与布尔值结合不起作用

问题描述

我正在生成一些对象,我有两种类型的碰撞,与地板或与厕所(玩家)。如果对象首先与地板发生碰撞,则存在延迟和破坏,但如果它接触到洗手间(玩家),可能会发生 2 件事:

  1. 直接接触,破坏。
  2. 触地后弹跳,不是被厕所破坏,而是因为前面提到的延迟。

所以带有布尔碰撞发生(真或假)的 if else 不起作用,我的意思是,地板工作正常,当物体接触地板时,它们被摧毁,但是当它们接触 Player 时,什么也没有发生。我的代码有问题:

private void OnCollisionEnter(Collision target)
{
    collisionHappened = true;

    if (target.gameObject.tag.Equals("bathroomFloor") == true && collisionHappened)
    {
        StartCoroutine(WaitToDestroy());

    }

    if (target.gameObject.tag.Equals("superToilette") == true)
    {
        if (collisionHappened)
        {

        }
        else if (collisionHappened != true)
        {
            Destroy(this.gameObject);
            GameObject.Find("scoreBoardText").GetComponent<ScoreBoard>().duringGameScoreIncreaser++;
        }
    }
}

一些建议?多谢你们!

标签: c#unity3d

解决方案


摆脱== true.

所以:

if (target.gameObject.tag.Equals("bathroomFloor") == true && collisionHappened)

变成:

if (target.gameObject.tag.Equals("bathroomFloor") && collisionHappened)

此外,您在顶部设置了 collisionHappened = true ,因此您也可以将其删除,从而导致:

if (target.gameObject.tag.Equals("bathroomFloor"))
 // Do some stuff

此外,如果与(超级)厕所发生碰撞,您什么也不做

if (collisionHappened)
{
   // Handle the collision here 
}

推荐阅读