Menu
CoddyTech

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; gives CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix.
  • float s = Math.Sin(x); gives CS0266: Cannot implicitly convert type 'double' to 'float', because System.Math works 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 icon

Challenge

Easy

The 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);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics