Search Unity

  1. Unity 2018.3 is now released.
    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. Want more efficiency in your development work? Sign up to receive weekly tech and creative know-how from Unity experts.
    Dismiss Notice
  4. Build games and experiences that can load instantly and without install. Explore the Project Tiny Preview today!
    Dismiss Notice
  5. Nominations have been announced for this years Unity Awards. Celebrate the wonderful projects made by your peers this year and get voting! Vote here!
    Dismiss Notice
  6. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    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:
    11
    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.