- Home /
Displaying velocity of a game object
Hi, I am working on to get a game object's velocity. I got stock on displaying the values
using UnityEngine;
using System.Collections;
public class UnitDisplayScript : MonoBehaviour {
void FixedUpdated()
{
speed = GameObject.rigidbody.velocity.magnitude;
}
void OnGUI()
{
GUI.Box(new Rect(10,10,100,90), "Measurements");
GUI.Label(new Rect(20,40,80,20), speed + "m/s");
}
}
GUI does appear on the left top corner of the display. Just that velocity does not change...
If it does display will it be resultant velocity? Also, how would I display vertical and horizontal velocity?
im trying to do the same but it will only display 0. any ideas?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class yeet : $$anonymous$$onoBehaviour {
private float speed;
void FixedUpdated()
{
speed = GetComponent<Rigidbody>().velocity.magnitude;
}
void OnGUI()
{
GUI.Box(new Rect(10, 10, 100, 90), "$$anonymous$$easurements");
GUI.Label(new Rect(20, 40, 80, 20), "velocity is:" + speed );
}
}
Please don't post questions as answers - it looks like your problem is that you copied the FixedUpdated typo... This should be changed to FixedUpdate else Unity won't call it and speed will remain zero.
Answer by Nanity · Jun 22, 2013 at 11:36 AM
GameObject is the class where all the objects inherit from, in order to access the specific gameObject, write it with a non-capital letter. Change
GameObject.rigidbody.velocity.magnitude
to one of those alternatives
gameObject.rigidbody.velocity.magnitude
rigidbody.velocity.magnitude
GetComponent<Rigidbody>().velocity.magnitude
Note that rigidbody and GetComponent< Rigidbody>() are identical, so you better cache the rigidbody parameter in the Start Function and use that one (_rigidbody) all the time:
private Rigidbody _rigidbody;
private void Start()
{
_rigidbody = rigidbody;
}
This may be micro optimizing, but as you plan to call this every frame it's worth a thought.
I am getting an error: "The name 'speed' does not exist in the current context"
using UnityEngine;
using System.Collections;
public class UnitDisplayScript : $$anonymous$$onoBehaviour {
void FixedUpdated()
{
speed = rigidbody.velocity.magnitude;
}
void OnGUI()
{
GUI.Box(new Rect(10,10,100,90), "$$anonymous$$easurements");
GUI.Label(new Rect(20,40,80,20), speed + "m/s");
}
}
What have I done wrong?
You have to declare the variable globally first and put it in line 5:
private float speed;
And like merry_christmas correctly noted the function should be called FixedUpdate() and not FixedUpdated(), otherwise it's not going to be called.