Search Unity

  1. Unity 2019.1 beta is now available.
    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. We're looking for insight from anyone who has experience with game testing to help us better Unity. Take our survey here. If chosen to participate you'll be entered into a sweepstake to win an Amazon gift card.
    Dismiss Notice
  4. On February 28th the Feedback website will shut down and be redirected to the Unity forums. See the full post for more information.
    Dismiss Notice
  5. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  6. Unity 2018.3 is now released.
    Dismiss Notice
  7. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    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:
    14
    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.