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?
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;
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 ContactPoint
s in Collision.contacts
and this : ContactPoint.otherCollider.gameObject
and check its name :)
Hope it helped :)
More info : Collision Contacts - Unity Docs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.