Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

how to create a speedometer (car game) ?

Discussion in 'Scripting' started by l4rthurl, Mar 17, 2015.

  1. l4rthurl

    l4rthurl

    Joined:
    Apr 10, 2014
    Posts:
    6
    I was trying to create a speedometer, but I don't know how to send the information (speed value) from the car to the gui text (speedometer). The script i used to get the car speed is right below:

    using UnityEngine;
    using System.Collections;

    public class velocimetro : MonoBehaviour {

    private int Velocidademodulo;
    private Vector3 posicaoAnterior,
    velocidade;
    // Use this for initialization
    void Start () {
    posicaoAnterior = transform.position;
    }

    // Update is called once per frame
    void FixedUpdate () {
    velocidade = (transform.position - posicaoAnterior) / Time.deltaTime;

    Velocidademodulo = (int) (velocidade.magnitude);

    print ("Vel - >" + Velocidademodulo);
    posicaoAnterior = transform.position;

    }
    Vector3 Velocidade {
    get {
    return this.velocidade;
    }

    }
    }

    * velocidademodulo is in portuguese, I'm from Brazil.
    With this, I'm able to get the car speed and print it on the console, and it works, but i would like to know how to take this information (speed value) and bring it into the void FixedUpdate instance of my speedometer script:

    [RequireComponent(typeof (GUIText))]
    public class veloc : MonoBehaviour
    {
    private int currentVelocidade;
    private string display = "{0} Km/h";
    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void FixedUpdate ()
    {
    GameObject.Find("car1");
    currentVelocidade = (int) (Velocidademodulo);
    guiText.text = string.Format(display, Velocidademodulo);

    }
    }
    I tought that by finding the gameobject in wich the variable "velocidademodulo" is defined should allow me to "import" the data inside the other script, but it didn't work. Hope someone can help me with this.
     
  2. soxroxr

    soxroxr

    Joined:
    Jul 17, 2012
    Posts:
    60
    If you are using the new Unity UI, try something like this;

    make a public object called "text"
    Code (csharp):
    1. public Text text;
    You will need to drag and drop the text element from the canvas that you wish to update onto the public field created on the script from whatever game object you have this attached to. (much less complicated than my wording would suggest)

    Then you'd just change it in your update function.

    Code (csharp):
    1. text.text  = currentVelocidade;
    2. //or if you want to display a string along with it
    3. text.text = currentVelocidade + "km/h";  //or mph or whatever you'd like
    I very much recommend against using "GameObject.Find()" as it's a fairly heavy operation, especially to do every update like you are. :)
    If you must use it, it's better to cache the information.

    In your Start() or Awake() functions, you'd simply add something like
    Code (csharp):
    1. GameObject currentCar = GameObject.Find("car1");
    then simply call "currentCar". (though I don't see you explicitly referring to the car it anywhere in what you posted.)
     
    l4rthurl likes this.
  3. l4rthurl

    l4rthurl

    Joined:
    Apr 10, 2014
    Posts:
    6
    soxroxr, i tried out your solution, but when i put in the code "public Text text;" to create the object, it shows me this "error CS0246: The type or namespace name `Text' could not be found. Are you missing a using directive or an assembly reference?". Is the code suposed to be like this:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4.  
    5. public class velocimetro : MonoBehaviour {
    6.  
    7.     public Text text;
    8.     private int Velocidademodulo;
    9.     private Vector3 posicaoAnterior,
    10.     velocidade;
    11.     // Use this for initialization
    12.     void Start () {
    13.         posicaoAnterior = transform.position;
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void FixedUpdate () {
    18.         velocidade = (transform.position - posicaoAnterior) / Time.deltaTime;
    19.      
    20.         Velocidademodulo = (int) (velocidade.magnitude);
    21.      
    22.         print ("Vel - >" + Velocidademodulo); //disconsider this
    23.         posicaoAnterior = transform.position;
    24.         text.text = Velocidademodulo + "km/h";  //or mph or whatever you'd like
    25.      
    26.     }
    27.     Vector3 Velocidade {
    28.         get {
    29.             return this.velocidade;
    30.         }
    31.      
    32.     }
    33. }
    ?
    Also, i tried changing "public Text text;" to "public GUIText text;", and when i do it, it creates a slot in the script component to assign a guitext, but it doesn't let me to assign any text objects i create.
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,787
    To use Text you need to add using UnityEngine.UI to the top of your script.
     
    soxroxr and l4rthurl like this.
  5. l4rthurl

    l4rthurl

    Joined:
    Apr 10, 2014
    Posts:
    6
    Thanks a lot BoredMormon, that was the only thing missing, now i got a working speedometer. Just to know, this speed value i get is measured meters/second? it is calculated by the formula deltaSpace/deltaTime (high school physics classes). Again, thanks for answering. If does anyone wants the code for reference (in case of facing the same problems i did), i am sharing it downhere:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5.     public class speedometer : MonoBehaviour {
    6.  
    7.     public Text text;
    8.     private double Speed;
    9.     private Vector3 startingPosition,
    10.     speedvector;
    11.     // Use this for initialization
    12.     void Start () {
    13.         startingPosition = transform.position;
    14.     }
    15.    
    16.     // Update is called once per frame
    17.     void FixedUpdate () {
    18.         speedvector = (transform.position - startingPosition) / Time.deltaTime);
    19.         Speed = (int) (speedvector.magnitude) * 3.6; // 3.6 is the constant to convert a value from m/s to km/h, because i think that the speed wich is being calculated here is coming in m/s, if you want it in mph, you should use ~2,2374 instead of 3.6 (assuming that 1 mph = 1.609 kmh)
    20.        
    21.         startingPosition = transform.position;
    22.         text.text = Speed + "km/h";  // or mph
    23.        
    24.     }
    25.     Vector3 speedvector {
    26.         get {
    27.             return this.speedvector;
    28.         }
    29.        
    30.     }
    31. }
     
    Last edited: Mar 18, 2015
    soxroxr likes this.
  6. soxroxr

    soxroxr

    Joined:
    Jul 17, 2012
    Posts:
    60
    Does this work well?
    I just woke up, but looking at it, it seems like there maybe issues if at any point you're not accelerating in a straight line away from startingPosition.


    Edit: Yeah, you can't change the first one, GUIText is the internal UI component name, and Text is the component name of the new UI text. If you want it to read as GUIText in the script, you'd set it as
    Code (csharp):
    1. public Text GUIText;
    Though, it only works to assign to the script if it's attached to a gameobject.
     
    Last edited: Mar 18, 2015
  7. l4rthurl

    l4rthurl

    Joined:
    Apr 10, 2014
    Posts:
    6
    it works because the positions is a vector3, so it has x,y and z coordinates wich together results in a position vector; what this formula does is simply calculate how fast did the body moved from one starting point (0,0,0 for example) to another point located at (3,2,5 for example); it works properly in straights, curves, or any type of trajectory, and also, it comes back a vector wich represents the speed (in this example, since deltatime is one second, we are going to have a speed vector formed by the coordinates (3-0/1 m/s, 2-0/1 m/s, 5-0/1 m/s), and this coordinates are the speed of the body on each axis. So, what you have to do here is to calculate the magnitude of this vector, to get its real value, instead of its value on each axis; to do this, unity simply calculate sqrroot(x^2 + y^2 + z^2) and returns you the real speed value.
     
  8. furrywolfboy53

    furrywolfboy53

    Joined:
    Apr 22, 2021
    Posts:
    3
    im having trouble creating movement for a main character and my brain is not quite yet developed enough to figure out what it means because i am in 7th grade can somebody tell me whats wrong on my script?

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class kitgo { MonoBehaviour

    // Start is called before the first frame update;
    Rigidbody ;rb
    newcharacterc71099cc41134ecf9d3d5594d3b3e153.fbx ([SerializeField] speed);
    rb GetComponent<Rigidbody>();

    void Update();


    void Update();
    float x = Input.GetAxisRaw("Horizontal");
    float z = Input.GetAxisRaw("Vertical");

    Vector3 moveBy = transform.right * x + transform.forward * z;

    rb.MovePositiontransform.position moveBy;normalized(speed Time,deltaTime16 milliseconds);}
     
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    14,303
    Nothing above is valid C# code, it's just random snippets of code-like gibberish.

    You may wish to consider starting here: https://unity.com/learn

    ALSO: Please do not post to six-year-old threads. Instead, start your own fresh thread, it's a) free and b) necessary according to forum rules.

    If you have an actual issue, here is how to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    How to understand compiler and other errors and even fix them yourself:

    https://forum.unity.com/threads/ass...3-syntax-error-expected.1039702/#post-6730855

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
    Kiwasi and Joe-Censored like this.
  10. furrywolfboy53

    furrywolfboy53

    Joined:
    Apr 22, 2021
    Posts:
    3
     
  11. furrywolfboy53

    furrywolfboy53

    Joined:
    Apr 22, 2021
    Posts:
    3
    ok sorry and thank you
     
    Joe-Censored likes this.
unityunity