【问题标题】:Multiple triggers in UnityUnity 中的多个触发器
【发布时间】:2017-07-13 13:23:06
【问题描述】:
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”
【问题讨论】:
标签:
c#
unity3d
collision-detection
game-engine
game-physics
【解决方案1】:
OnTriggerEnter 仅在您的对象与一个特定触发器发生碰撞时调用。因此,对撞机的标签(col)不能同时为speed和point。
您必须使用布尔变量来跟踪对象是否与触发器发生碰撞:
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;
}
}
【解决方案2】:
虽然@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);
}
理论上,这在性能方面的效率要低得多(与存储布尔值相比),但仍然是,它增加了一层很好的灵活性。
在实践中,性能差异非常小,所以您自己决定!