- Home /
How do I assign the velocity on the "y" axis to a float?
Hi there, MEGA NOOB here (=
A really simple question but I just can't seem to get it right. I'm playing around with the animator, I've got a parameter "AboutToStop" and I'd like to set it to the velocity of the y axis (float vel) so I can change animation with transitions based on the velocity.
Thanks in advance !
......
Animator anim;
float vel;
void Start()
{
anim = GetComponent<Animator> ();
}
void Update()
{
vel = GetComponents<Rigidbody2D>().velocity.y;
anim.SetFloat ("AboutToStop", vel);
}
..........
Comment
Answer by HarshadK · Apr 03, 2015 at 05:22 AM
You need to use GetComponent instead of GetComponents like:
vel = GetComponent<Rigidbody2D>().velocity.y;
But since you should not use GetComponent every Update you can cache it as below:
Rigidbody2D rigidbody2D;
Animator anim;
float vel;
void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator> ();
}
void Update()
{
vel = rigidbody2D.velocity.y;
anim.SetFloat ("AboutToStop", vel);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613192035im_/https://answers.unity.com/themes/thub/images/avi.jpg)