InvalidCastException Inconsistancy

Maybe I’m just getting tired, but I getting this error:
InvalidCastException: Cannot cast from source type to destination type.
Yet it looks like they are of the same type?

Not only that, but the code was cut and pasted from another editor with a similar structure (for another scripts), and it works fine.

using UnityEngine;
using UnityEditor;

[CustomEditor (typeof (MF_B_ObjectPoolManager))]
public class MF_B_ObjectPoolManager_Editor : Editor {

    SerializedObject obj;
    MF_B_ObjectPoolManager script;

    void OnEnable () {
        obj = new SerializedObject( target );
        script = (MF_B_ObjectPoolManager) target; // <--- ERROR HERE!
    }
...

I just changed the offending line to:
script = target as MF_B_ObjectPoolManager; // <--- NO ERROR!And now it works.

But why would it work only one way in one script, and the other in another script?

‘as’ doesn’t throw an exception, if it fails it returns null.

Where as (TypeName) will throw an exception.

So that’s why you won’t get an error… are you sure ‘script’ is a thing after doing the ‘as’?

1 Like

It works in both variations, despite the error.

Hmmm… It actually turns out it’s null at that moment.

But then later becomes a thing after:

public override void OnInspectorGUI ( ) {
    obj.Update();

Simply moving it after obj.Update() removes the error.

However… this doesn’t really explain why it was not throwing an error in the other script.