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
EasyMake the heart's script compile so it pulses again.
- On the
sizeline, changeMath.AbsandMath.SintoMathf.AbsandMathf.Sin. - Change
0.5to0.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
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