Unity 中的多个触发器



参考图片

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

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

如何识别对象是否仅命中"Col1"或"Col1"和"Col2">

仅当对象与一个特定触发器发生冲突时,才会调用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;
}
}

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

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

最新更新