Why is it that if using OnCollision method I have to use
private void OnCollisionEnter2D ( Collision2D collision )
{
Debug.Log ( "Hit " + collision.transform.name );
IDamageble hit = collision.transform.GetComponent<IDamageble>();
}
and if using OnTrigger method I have to use the code below?
private void OnTriggerEnter2D ( Collider2D collision )
{
IDamageble hit = collision.GetComponent<IDamageble>();
}
:/ Why is it that I can access the component without first accessing the transform in one method and not in the other?
Because OnTriggerEnter2D does not get a special Collision class but simply the collider that has entered the trigger area. You just named your collider “collision” for some reason. Any Component derived class has a GetComponent method to access other components on the same gameobject. This is essentially a shorthand for using GetComponent on the gameobject of the component.
You may want to rename your variable as it’s non descriptive and confusing as it doesn’t represent a “collision” but simply a “collider”.
Just to make it more clear, have a look at the documentation of OnTriggerEnter2D. It has a Collider2D parameter, not a Collision2D parameter.
Also note that in your first case it would be slightly faster to use
collision.gameObject.GetComponent<IDamageble>();
instead of
collision.transform.GetComponent<IDamageble>();
Since the component version of GetComponent will in turn call the one on the GameObject of that component.