在 Unity3D 中检测玩家死亡的两个标签

Detecting two tags in Unity3D for player death

我正在制作一个 classic 陷阱,两堵墙合在一起砸玩家。为此,我创建了两个单独的标签,"Crush" 和 "Crush1",并为每面墙分配了一个标签。这是我播放器上的代码 class:

void OnCollisionEnter(Collision other)
{
    if (other.transform.tag == "Crush" && other.transform.tag == "Crush1")
    {
        Die ();
    }
}

我只希望玩家在两面墙同时接触到玩家时被摧毁。当我删除参数中的一个标签时,该方法工作正常(只是不是我想要的)。我确定这里有一个简单的解决方法,我只是没有看到它。感谢您的帮助!

您可以做的是使用以下代码创建一个脚本并将其附加到您的两个 Wall 对象:

public class WallScript : MonoBehaviour
{
    [HideInInspector]  //Optional Attribute
    public bool collidedWithPlayer;

    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.name == "Player")
        {
            collidedWithPlayer = true;
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if(collision.gameObject.name == "Player")
        {
            collidedWithPlayer = false;
        }
    }
       //We don't want "collidedwithPlayer" to remain true if either of the walls touches the player before both do so we call "OnCollisionExit" to set it to false.
}

然后在播放器脚本中执行以下操作:

  private WallScript wall1Script;
  private WallScript wall2Script;

  private void Awake()
  {
      wall1Script = GameObject.Find("Wall1").GetComponent<WallScript>();
      wall2Script = GameObject.Find("Wall2").GetComponent<WallScript>();
  }

   private WallScript wall1Script;
   private WallScript wall2Script
   public GameObject wall1;
   public GameObject wall2;  //Assign GameObjects in Inspector

   private void Awake()
   {
       wall1Script = wall1.GetComponent<WallScript>();
       wall2Script = wall2.GetComponent<WallScript>();
   }

然后在同一个脚本中:

  private void Update()
  {
      if(wall1Script.collidedWithPlayer && wall2Script.collidedWithPlayer)
      {
         //Do Something here
      }
  }

你知道,当玩家碰到两堵墙时。 函数 OnCollisionEnter 将被执行两次。 第一次,other.transform.tag == "Crush" 为真。 第二次,other.transform.tag == "Crush1" 为真。 在 OnCollisionEnter 中,other 只有一个标签。 tag == tag1 && tag == tag2 if tag1 != tag2

永远不会是真的

@Christiopher G 说得对,你需要在旗帜击中你时存储它们(并停止击中你)。

我认为他的代码有点臃肿,因为不需要新的 class,您当前的代码很容易扩展以执行您想要的操作。

注意:Unity 目前不可用,因此未经测试。

bool wall1 = false;
bool wall2 = false;

void Update()
{
    if( wall1 && wall2 )
    {
        Die();
    }
}

void OnCollisionEnter(Collision other)
{
    if (other.transform.tag == "Crush")
    {
        wall1 = true;
    }
    else if(other.transform.tag == "Crush1")
    {
        wall2 = true;
    }
}


void OnCollisionExit(Collision other)
{
    if (other.transform.tag == "Crush")
    {
        wall1 = false;
    }
    else if(other.transform.tag == "Crush1")
    {
        wall2 = false;
    }
}