How can I detect if a gameObject has collided with two other specific objects at the same time?

别等时光非礼了梦想. 提交于 2019-12-12 03:28:25

问题


How can I detect if a gameObject has collided with two other specific objects at the same time?

This is what I intend to do but it does not work:

void OnCollisionEnter (Collision col)
{

if(col.gameObject.name == "object1" && "object2")
    {
        Destroy(gameObject);
    }
}

How can I correct this piece of code?


回答1:


If you are colliding with 2 objects the method OnCollisionEnter will be called twice, so you must keep track of their gameobject or names.

List<string> contacts = new List<string>();
void OnCollisionEnter (Collision col)
{
    contacts.Add(col.gameObject.name);
    if(contacts.Contains("object1") && contacts.Contains("object2"))
    {
        Destroy(gameObject);
    }
}
void OnCollisionExit(Collision col)
{
    contacts.Remove(col.gameObject.name);
}

but remember to add the reference to get the lists to work

using System.Collections.Generics;



回答2:


IF you are checking collisions on any of the events fired regarding collison, like Collider.OnCollisionEnter Collider.OnCollisionStay Collider.OnCollisionExit, you could get ALL the Contact points from the Collision parameter passed by the event by

Collision.contacts and you could get the gameObject by Enumerating the ContactPoints in Collision.contacts and this : ContactPoint.otherCollider.gameObject and check its name :)

Hope it helped :)

More info : Collision Contacts - Unity Docs



来源:https://stackoverflow.com/questions/32923585/how-can-i-detect-if-a-gameobject-has-collided-with-two-other-specific-objects-at

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!