Playing around collision and the Debug.Log()
, I have confirmed that OnTriggerEnter
triggers in a specific order; that is, when carA moves into carB, it will set off the OnTriggerEnter
method attached to carB. This always seems to happen first, with the OnTriggerEvent
method attached to carA triggering, second.
Working off of the answer submitted by Vadim Tatarnikov, I set up bool collisonInstigator
that typically defaults as false
. I was than able to check for collisionInstigator == true
during OnTriggerEnter
. If collisionInstigator == false
, we assume that the other
collider is the instigator, and set other.<script>.collisionInstigator = true
. When the instigators OnTrigger
method calls, which we can assume will be directly after the first, we find that collisionInstigator == true
.
This tells us that we are currently in the OnTrigger
method for the car that started the collision, allowing us to run our logic as required. The only other thing we have to do is ensure that we set collisionInstigator = false
at the end of our logic, to set it back up for the next potential collision scenario, assuming your not calling for the instigator to be destroyed or any other logic that would make further collisions with that game object impossible.
public class CarAI : MonoBehaviour
{
public bool collisionInstigator = false;
void OnTriggerEnter(Collider other)
{
if(collisionInstigator == true)
{
// I am crashing into the other car; run logic
DebugCollision(other.gameObject); // confirm order through debug
collisionInstigator = false; // don't forget to reset the flag!
}
else
{
// I am being crashed into by the other car
other.GetComponent<CarAI>().collisionInstigator = true;
}
}
///<summary>Using tags, we can double check our logic regarding which GameObject
/// is the "instigator"</summary>
void DebugCollision(GameObject other)
{
string myName = gameObject.name;
string otherName = other.gameObject.name;
Debug.Log(myName + " is colliding with " + otherName);
}
}
Using DebugCollision(GameObject other)
to debug a clearer formatted string of the collision, I confirmed that the above script will correctly pick the "instigator" across a variety of speeds, using both Transform.Translate()
and RigidBody.AddForce()
methods.