- Home /
error CS0664: Literal of type double cannot be implicitly converted to type `float'. Add suffix `f' to create a literal of this type
Can anybody please tell me what this error means? Well here is my script. Please correct any other mistakes I made.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(PlayerPhysics))]
public class PlayerController : MonoBehaviour {
public float speed = 8;
public float acceleration = 12;
private float currentSpeed;
private float targetSpeed;
private Vector2 amountToMove;
private PlayerPhysics playerPhysics;
// Use this for initialization
void Start () {
playerPhysics = GetComponent<PlayerPhysics>();
}
// Update is called once per frame
void Update () {
targetSpeed = Input.GetAxisRaw ("Horizontal") * speed;
currentSpeed = IncrementTowards (currentSpeed, targetSpeed, acceleration);
}
private float IncrementTowards(float n, float target, float speed) {
if (n == target) {
return 0.0; //this is the line it says the error was on.
} else {
float dir = Mathf.Sign (target - n);
n += Time.deltaTime * dir;
return (dir == Mathf.Sign (target - n)) ? n : target;
}
}
}
Answer by supernat · Mar 10, 2014 at 10:03 PM
The error is quite explicit. There are multiple types of floating point values. The type float is 4 bytes long and type double is 8 bytes long, which gives double more precision than float. As such, when you declare a literal, say "0.2", the compiler needs to know precisely what type you are using. Leaving it without a postfix character means it's a double (i.e. 0.2, 1.4, 3.435545). Add "f" to the end to tell the compiler it is a float (0.2f, 1.4f, etc). Additionally, to make things more confusing, if you leave off the decimal point, that is also valid. In your case, you can say 0, instead of 0.0. The compiler knows you are safe to use a floating point since you have nothing after the decimal, so precision is not a concern. Also, you can use 0.0f. I almost wish they would allow 0.0, but then we would get lazy.
Well im glad I understood that because a month ago I wouldn't. Thanks
oh and if it new I needed to add f why didn't it just do it for me?
You don't want compilers making decisions for you. In some situations the right fix for this error might be to change the return type of the function to double rather than change the literal to a floating point number. Having the compiler fix this can lead to subtle and difficult to find bugs. The compiler might get it right 999/1000 times, but that 1000th time can lead to a world of pain for the programmer.
Your answer
Follow this Question
Related Questions
Scrolling Repeated Background - background is scrolling but not repeating 0 Answers
How To Make 2D Side Scrolling Game 3 Answers
Constraining Physics 3 Answers