Home > front end >  How to Show SpeedMeter on Screen in Unity
How to Show SpeedMeter on Screen in Unity

Time:09-22

I added Speedmeter to my project but it doesnt work. Just stays in 0. I completely new in C#. Project is 2D. Here is code;

public Text text;
private double Speed;
public float speed0 = 0;

void Start()
{
    text.text = Speed.ToString();
    startingPosition = transform.position;
}
Vector3 startingPosition = Vector3.zero;

void FixedUpdate()
{
    speed0 = ((transform.position - startingPosition).magnitude / Time.fixedDeltaTime);
    startingPosition = transform.position;

    text.text = GetComponent<Rigidbody2D>().velocity.magnitude   " km/h ";


}

enter image description here

CodePudding user response:

Try replacing GetComponent().velocity.magnitude with the unused var speed0

CodePudding user response:

This is all the code you need to have the text represent the speed on the x-axis in real time.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class NewBehaviourScript1 : MonoBehaviour
{
    [SerializeField] TMP_Text text;
    [SerializeField] GameObject cube;
    [SerializeField] float speed;

    Rigidbody cubeRb;

    void Start()
    {
        cubeRb = cube.GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        var deltaSpeed = Mathf.Abs(cubeRb.velocity.x) * Time.deltaTime * speed;
        text.text = deltaSpeed   " km/h ";
    }
}

The speed variable allows you to tweak the km/h indicator to your preferences.

Use TMPro package when you do anything text-related. It adds more flexibility and everyone uses it.

[SerializeField] is the same as making your variables public, with the extension that they belong only to this class. It's a standart to not declare them as public.

Let me know if you have any other questions.

  • Related