Unity 中的多个触发器

Multiple triggers in Unity

Reference image

我的游戏中有一个特定的对象,我正在尝试查看该对象是否会触发多个触发器。我尝试使用下面的代码,但由于某种原因它不起作用。

void OnTriggerEnter2D(Collider2D col)
{
    if (col.tag == "speed")
    {
        //do something
    }
    else if (col.tag == "speed" && col.tag == "point")
    {
        //do something
    }
}

我如何识别对象是否只命中 "Col1" 或 "Col1" 和 "Col2"

OnTriggerEnter 仅在您的对象与 一个特定触发器 发生碰撞时调用。因此,collider(col)的标签不能同时为speedpoint

您必须使用布尔变量跟踪对象是否与您的触发器发生碰撞,例如:

private bool collidingWithSpeed;
private bool collidingWithPoint;

void OnTriggerEnter2D(Collider2D col)
{
    if (col.CompareTag("speed"))
    {
        collidingWithSpeed = true ;
        //do something
    }
    else if (col.CompareTag("point"))
    {
        collidingWithPoint = true ;
        //do something
    }

    if( collidingWithSpeed && collidingWithPoint )
    {
         // Do something when your object collided with both triggers
    }
}
// Don't forget to set the variables to false when your object exits the triggers!
void OnTriggerExit2D(Collider2D col)
{
    if (col.CompareTag("speed"))
    {
        collidingWithSpeed = false;
    }
    else if (col.CompareTag("point"))
    {
        collidingWithPoint = false;
    }
}

虽然@Hellium 的回答会很完美,但我个人更喜欢使用列表来存储我所有的碰撞对象(或至少其中一些)。像这样

private readonly List<string> collidingTags = new List<string>();

void OnTriggerEnter2D(Collider2D collider)
{
    //Add some kind of filter or safety check if needed
    collidingTags.Add(collider.tag);
}

void OnTriggerExit2D(Collider2D collider)
{
    //Add some kind of safety check if needed
    collidingTags.Remove(collider.tag);
}

从理论上讲,这在性能方面的效率要低得多(与存储布尔值相比),但它仍然增加了一层很好的灵活性。 在实践中,性能差异非常小,所以你来决定!