Animation Event object reference parameter cannot be casted correctly

I have a Function1.cs and Function2.cs. Function 1 is added under Animation Tab->Add Event->Inspector for Animation Event->Object parameter->Under Asset. When I run the game, I have “InvalidCastException. Cannot cast from source type to destination type.” for line 1.

Any advice please?

Thank you.

public void Function1(Object obj)
{
    MyClass myClass = (MyClass)obj;        // Line 1
    StartCoroutine(Function2(myClass));       
}



IEnumerator Function2 (MyClass obj1)
{           
    foreach (int item in obj1.objArray)
    {
        print(item);               
    }
    yield return null;
}

obj.GetType() != typeof(MyClass). The parameter obj is not of type MyClass, you should look at interface.

What do you want to do exactly ? Why you can"t put :

public void Function1 (MyClass obj)
{

}

?

I’m going to guess that the Object that’s sent in is the linked GameObject, while you want a MonoBehaviour attached to that object.

I wanted to run Function1 method when a certain animation clip is activated, through the use of animation event. This method was passed in by adding the script object Function1.cs (the codes in original post are in Function1.cs) located under Animation Tab->Add Event->Inspector for Animation Event->Object parameter->Under Asset->Function1.cs.

What is the correct way to access the member variable (in this case the objArray) through the object reference passed in from the animation event inspector? This example works when Function1(Object obj) is called from Function2.cs (not through animation event).

//Function2.cs//

public Function1 function1;
public MyClass myClass;

function1.Function1(myClass);

//Function1.cs//

public void Function1(Object obj)
{
    MyClass myClass = (MyClass)obj;        // Line 1
    StartCoroutine(Function2(myClass));     
}
IEnumerator Function2 (MyClass obj1)
{         
    foreach (int item in obj1.objArray)
    {
        print(item);             
    }
    yield return null;
}

@CrymX The function called by an Animation Event has the option to take one parameter, of which it has to be a float, string, int, or object reference, or an AnimationEvent object. Hence I can’t use (MyClass obj) as parameter

From looking at AnimationWindowEventInspector.cs:

...
if (selectedParameter == typeof(AnimationEvent) || selectedParameter.IsSubclassOf(typeof(UnityEngine.Object)) || selectedParameter == typeof(UnityEngine.Object))
...

So your class must either be a UnityEngine.Object or inherit from UnityEngine.Object