问题
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