Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Let us know a bit about your interests, and if you'd like to become more directly involved. Take our survey!
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

How do I convert String to Float

Discussion in 'Scripting' started by Carterthepro, Oct 13, 2018.

  1. Carterthepro

    Carterthepro

    Joined:
    Apr 25, 2017
    Posts:
    3
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class Calculator : MonoBehaviour {
    5.     public InputField Mass;
    6.     public InputField Acceleration;
    7.     public float Force;
    8.     public Text ForceText;
    9.     public float MassNum;
    10.     public float AccelerationNum;
    11.     // Use this for initialization
    12.     void Start () {
    13.  
    14.     }
    15.    
    16.     // Update is called once per frame
    17.     void Update () {
    18.         float AccelerationNum = float.Parse(Acceleration.text);
    19.         float MassNum = float.Parse(Mass.text);
    20.  
    21.         Force = AccelerationNum * MassNum;
    22.         ForceText.text = Force.ToString();
    23.     }
    24. }
    25.  
    Thx I tried this
     
  2. phaskins928

    phaskins928

    Joined:
    May 3, 2018
    Posts:
    5
    You really should put your parsing code for your float into a try catch block so it doesn't throw a error
    Code (CSharp):
    1. void Update()
    2.     {
    3.         try
    4.         {
    5.             float AccelerationNum = float.Parse(Acceleration.text);
    6.             float MassNum = float.Parse(Mass.text);
    7.  
    8.             Force = AccelerationNum * MassNum;
    9.             ForceText.text = Force.ToString();
    10.         } catch(Exception e) {
    11.             print(e.ToString());
    12.         }
    13.     }
    Also next time please go into more detail on what breaks so it is easier to help you.