Decimals Need an f
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 3 of 85.
Whole numbers are not enough for a game: a balloon floats at 3.5, a player runs at 4.2 units a second. Numbers with a decimal point have their own type, float:
float speed = 4.2f;Notice the f at the end. In C#, a plain 4.2 is a double, another decimal type, and Unity's positions and sizes are floats. The f tells C# the number is a float. Leave it out and Unity refuses to start the game, with this error in the Console:
error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this typeIt looks scary, but it only means "add the f". A whole number like 2 needs no f: it fits in a float as it is.
One more surprise: dividing two ints keeps only the whole part, so 7 / 2 is 3. Write 7 / 2f to get 3.5.
Challenge
EasyFix the balloon's script, then make it float higher and bigger.
- Press Play: the Console shows error CS0664 on the
heightline. - Change that line to
float height = 3.5f;. - Change the size line to
float size = 1.5f;. Every number with a decimal point needs itsf.
Press Play: the balloon floats at 3.5, one and a half times its size. Then Check.
Try it yourself
using UnityEngine;
public class Balloon : MonoBehaviour
{
void Start()
{
float height = 2.5;
float size = 1;
transform.position = new Vector3(0, height, 0);
transform.localScale = new Vector3(size, size, size);
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground