- Home /
error CS0266: Cannot implicitly convert type `double' to `float'. An explicit conversion exists (are you missing a cast?) whats wrong?
hello i am making a spawner with timers and this error popped up i dont get it so do you guys know the answers here is my script and the error is: error CS0266: Cannot implicitly convert type double' to
float'. An explicit conversion exists (are you missing a cast?)
using UnityEngine;
using System.Collections;
public class spawner : MonoBehaviour {
public float WaitTime;
public GameObject Box;
public float DifChangeTime;
private float Timer;
private float DifTimer;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Timer += Time.deltaTime;
if (Timer > WaitTime) {
transform.position = new Vector3 (Random.Range (197, 204), 30, Random.Range (155, 162));
Timer = 0;
Instantiate (Box, transform.position, Quaternion.identity);
}
if(DifTimer > DifChangeTime) {
WaitTime = WaitTime - 0.5;
DifTimer = 0;
}
if (WaitTime > 0.5) {
DifTimer += Time.deltaTime;
} else {
DifTimer = 0;
}
}
}
thanks for helping
Not visible in the piece of code, try changing
private double Another;
to
private float Another;
cheers
that isnt working but I will remove it thank you for the reply
Answer by fafase · Jun 23, 2015 at 07:29 PM
WaitTime is a float but 0.5 is a double. Both are not the same type so they cannot be compared.
0.5f with the f extension makes it s float. This is only necessary when using a dot.
WaitTime = WaitTime - 0.5f;
if (WaitTime < 0.5f)
Just want to add that you usually can compare a float to a double as the compiler is allowed to up-cast a float value to a double implicitly. What is not allowed is an implicit down case from double to float as float has less precision.
So the operation:
WaitTime - 0.5;
// (float) (double)
will result in a double value as the float value (WaitTime) will be automatically converted to double.
However when you assign this result back to WaitTime it will throw an error as you can't assign a double value to a float variable without an explicit cast.
Of course the comparison should also use a float literal value as the conversion to double is unnecessary and might cause other problems.
ps: The same rule applies for the types "int" and "float". "int" to "float" will be done implicitly but not reverse.