Unity中的多个触发器

时间:2017-07-13 13:23:07

标签: c# unity3d collision-detection game-engine game-physics

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”

2 个答案:

答案 0 :(得分:7)

仅当您的对象与一个特定触发器发生碰撞时,才会调用

OnTriggerEnter。因此,对撞机的标签(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;
    }
}

答案 1 :(得分:1)

虽然@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);
}

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