Menu
CoddyTech

Floats and Mathf

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 16 of 85.

You met the f in Decimals Need an f: C# reads 0.5 as a double, and Unity counts in float. The same thing happens with math. System.Math works in doubles, so float s = Math.Sin(x); fails with CS0266: Cannot implicitly convert type 'double' to 'float'.

Unity has a float version of it, Mathf: 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

Make the heart's script compile so it pulses again.

  1. On the size line, change Math.Abs and Math.Sin to Mathf.Abs and Mathf.Sin.
  2. Change 0.5 to 0.5f, and keep the rest of the formula.

Press Play: the heart grows from 1 to 1.5 and back, about once a second. 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);
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground