Floats and Mathf
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 9 of 67.
Unity counts in float: positions, speeds, angles and Time.deltaTime are all floats. C# reads 0.5 as a double and will not squeeze a double into a float without being told, because it could lose precision. Two compile errors come from this in almost every beginner's first scripts:
float half = 0.5;givesCS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix.float s = Math.Sin(x);givesCS0266: Cannot implicitly convert type 'double' to 'float', becauseSystem.Mathworks in doubles.
The fixes: write float literals with f, and use Mathf, Unity's float version of Math (Mathf.Sin, Mathf.Abs, Mathf.Sqrt, Mathf.PI). This bobbing buoy failed with both errors and compiles after:
// before: float y = 1 + Math.Sin(Time.time * 2) * 0.5;
float y = 1 + Mathf.Sin(Time.time * 2) * 0.5f;
transform.position = new Vector3(0, y, 0);Whole numbers such as 1 and 2 need no suffix: an int turns into a float without any loss.
Challenge
EasyThe heart should pulse: its size goes from 1 up to 1.5 and back, three times a second, the same on every axis. The script does not compile. Fix the errors with Unity's float math, and keep the formula the same.
Press Play to see the errors in the Console, fix them, then Check.
Try it yourself
using System;
using UnityEngine;
public class Pulse : MonoBehaviour
{
void Update()
{
float size = 1 + Math.Abs(Math.Sin(Time.time * 3)) * 0.5;
transform.localScale = new Vector3(size, size, size);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon