Search Unity

  1. Unity 2019.1 is now released.
    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:
    14
    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. Twiddio

    Twiddio

    Joined:
    May 3, 2018
    Posts:
    26
    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.