- Home /
Show speed in UI
Hello,
I have a question, I want to show the speed of my script as a text value in the top left of the screen. From 0% to 100%.
My script is this using UnityEngine; using System.Collections;
[System.Serializable]
public partial class molen : MonoBehaviour
{
public float molensnelheid;
public Rigidbody arm;
public AudioSource Audio;
public bool motorpower;
public virtual void Update()
{
GetComponent<AudioSource>().pitch = molensnelheid / 70;
this.GetComponent<HingeJoint>().useMotor = true;
if (Input.GetKey("q"))
{
this.molensnelheid = this.molensnelheid + (-1 * Time.maximumDeltaTime);
}
if (Input.GetKey("a"))
{
if (this.molensnelheid < 0)
{
this.molensnelheid = this.molensnelheid + (1 * Time.maximumDeltaTime);
}
if (this.molensnelheid > 0)
{
this.molensnelheid = this.molensnelheid - (1 * Time.maximumDeltaTime);
}
if ((this.molensnelheid > -1.2f) && (this.molensnelheid < 1.2f))
{
this.molensnelheid = 0;
}
}
{
int _7 = 2000;
JointMotor _8 = this.GetComponent<HingeJoint>().motor;
_8.force = _7;
this.GetComponent<HingeJoint>().motor = _8;
}
{
float _9 = this.molensnelheid;
JointMotor _10 = this.GetComponent<HingeJoint>().motor;
_10.targetVelocity = _9;
this.GetComponent<HingeJoint>().motor = _10;
}
{
bool _11 = false;
JointMotor _12 = this.GetComponent<HingeJoint>().motor;
_12.freeSpin = _11;
this.GetComponent<HingeJoint>().motor = _12;
}
this.molensnelheid = Mathf.Clamp(this.molensnelheid, -100, 100);
}
public virtual void Start()
{
this.GetComponent<HingeJoint>().anchor = new Vector3(0, 1, 0);
this.GetComponent<HingeJoint>().axis = new Vector3(0, 1, 0);
}
}
I want to show the "public float molensnelheid;" as a value on the screen. But i'm not sure on how to that. I hope someone can help me with this :)
Answer by FlorentAlbyon · Aug 07, 2020 at 02:55 PM
Not sure what molenselheid is but if you're juste looking to display a text the simplest solution is:
create a Text game object (right click in hierarchy, UI > Text).
Create a serializable field in your "molen" monobehavior. Just add:
public Text myText;
(You will need to add "using UnityEngine.UI" at the top of your file)
then you just need to change the text value of your Text ui component in the update
myText.text = molensnelheid.ToString();
Note: You don't have to use "this" everytime :)
Hope this helps
That totally works. But how can I add a percentage? " int _7 = 2000;" "2000" is the maximum.
Thanks in advance :)
To add a percentage, you'll just have to compute it yourself, then display it in the same way. something like:
float percentage = (yourValue * 100f)/maxValue;
Also if you want to display a "%" sign in the text, you can juste concatenate strings together like so:
myText.text = percentage.ToString() + "%";
Your answer
![](https://koobas.hobune.stream/wayback/20220613005123im_/https://answers.unity.com/themes/thub/images/avi.jpg)