Invalid casts occur when an instance is converted to a type it does not match.
Type casting looks like this:
var end = (Type)start;
and is called a cast expression.
Understand the types involved in your expression. The object must inherit the type it's being casted to, or must have a user-defined conversion to that type.
Instantiate
If Instantiate
is throwing the exception, then the original type of the object has been changed.
Re-assign the object you are instancing in the Inspector to fix the type mismatch.
If you are using a foreach with Transform
then you must use the Transform
type for the elements. No other type will work.
//
Incorrect, Example is not a Transform type.
foreach (Example item in transform)
...
//
Correct, the type used is Transform
foreach (Transform item in transform)
...
Foreach across other collections may have similar issues if you attempt to cast to a type unsupported by the usage.
If your issue was not listed, please report an issue with this page so this page can be improved.