How can I access the AnimationState component?
Hey everyone,
I'm having a Sprite with an Animator component and when I'm trying to access the AnimationState I'm getting this error:
ArgumentException: GetComponent requires that the requested component 'AnimationState' derives from MonoBehaviour or Component or is an interface.
This is the relevant code part:
Transform test = BIG_parent.transform.FindChild("big2D").gameObject.transform.FindChild("big_idle_0");
anim2dState = test.GetComponent<Animator>().GetComponent<AnimationState>();
I also tried test.gameObject.GetComponent<Animator>().gameObject.GetComponent<AnimationState>();
or test.gameObject.GetComponent<AnimationState>();
or various combinations of these variants.
The class that contains this code inherits MonoBehaviour. AnimationState apparently inherits from TrackedReference, which is depricated and has no documentation.
I can't use the Animation component instead of the animator, because I need to be able to set the Speed parameter of the Animator to -1, and I need the AnimationState to access the AnimationState.length and AnimationState.time
I can post more code or information if you need it. Thanks for your time.
A year ago @chrisholdem wrote that there is no way to access the AnimationState without an animation component. Is this still true untill today? http://answers.unity3d.com/questions/1002400/how-do-i-set-the-time-of-an-animation-playing-in-t.html Heres what I'm trying to do:
I have the top down view of a sailboat sprite. There is an animation for the moving sail - if the boat adjust it's position relativ to the wind, the sail should move accordingly. The animation contains 60 frames from "Sail is as far left as possible" to "Sail is as far right as possible". If I steer a little bit to the right, the animation should play some frames forward and stop. If I steer a little bit to the left, the animation should play some frames backward and stop.
I also tried to use GetComponent(typeof(AnimationState))m but then I get a warning that UnityEngine.Component can't be converted into UnityEngine.AnimationState
Answer by Jonas_F · Sep 08, 2016 at 03:58 PM
Ok, I think I found a work around. Animator has the GetCurrentAnimatorStateInfo()
method, and it looks as if this method can give me all the information I need. At least I'm not getting error messages anymore.
Animator test = BIG_parent.transform.FindChild("big2D").gameObject.transform.FindChild("big_idle_0").gameObject.GetComponent<Animator>();
AnimatorStateInfo currentState = test.GetCurrentAnimatorStateInfo(0);
animationTime = currentState.normalizedTime;
targetTime = ((TWA + 180) / 360) * currentState.length;