GetComponent() Error :Cannot cast from source type to destination type.

The error : InvalidCastException: Cannot cast from source type to destination type.

appears when I use this piece of code:

var PolyCol : PolygonCollider2D[];
function Start(){
	PolyCol = GetComponents(PolygonCollider2D);
}

The gameobject with this code on it has 5 PolygonCollider2D attached to it.

Any ideas on why this error is appearing??

And can you explain what this means to me? :slight_smile:

1 Answer

1

GetComponents returns Component, not PolygonCollider2D; the error means that you canโ€™t convert from one to the other. (Which, yes, makes it inconsistent with GetComponent, which returns Type rather than Component.) You can use the generic version: GetComponents.< PolygonCollider2D >().